python - 使用 Python BeautifulSoup 库解析 Span HTML 标签中的信息

标签 python html web-scraping beautifulsoup

我正在编写一个 Python 网络抓取工具,用于抓取某只股票的价格。在我的程序结束时,有一些打印语句可以正确解析 html 数据,因此我可以在某个 HTML span 标记内获取股票的价格信息。我的问题是:我该怎么做?我已经得到了正确的 HTML span 标签。我以为您可以简单地进行字符串拼接,但是股票的价格会不断变化,我认为这种解决方案不利于解决这个问题。我最近开始使用 BeautifulSoup,所以我将不胜感激。

import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

# webscraping reference http://altitudelabs.com/blog/web-scraping-with-python-and-beautiful-soup/

my_url = 'https://quotes.wsj.com/GRPS/options'
#opens up a web connection and "downloads"a copy of the desired webpage
uClient = uReq(my_url)

#dumps the information read on the webpade into a variable for later use/parsing
page_html = uClient.read()
uClient.close()

page_soup = soup(page_html, "lxml")

#find the html location for the price of the stock
#<span id="quote_val">0.0008</span>

all_stock_info = page_soup.find("section",{"class":"sector cr_section_1"})
find_spans = all_stock_info.find("span",{"id":"quote_val"})
price = page_soup.findAll("span",{"id":"quote_val"})

#sanity checks to make sure the scraper is finding the correct info
print(all_stock_info)
print(len(all_stock_info))
print(len(price))
print(price)  #this gives me the right span, I just need to be able to parse 
              #the price of the stock between here (in this case 0.0008) no 
              #matter what the price is
print(all_stock_info.span)
print(find_spans)


  

最佳答案

您可以使用 .find.text 函数来获取所需的值。

例如:

from bs4 import BeautifulSoup
page_soup = BeautifulSoup(html, "lxml")
price = page_soup.find("span",{"id":"quote_val"}).text
print( price )

输出:

0.0008

关于python - 使用 Python BeautifulSoup 库解析 Span HTML 标签中的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51238622/

相关文章:

python - 在 Python 中创建大小为 n 的零向量

python - python 中的特征选择

html - 无法附加 AngularJS 数组

python - 单击网站上的按钮然后抓取网页

vba - 无法使用 xhr 从网页中获取一些信息

python - EMAIL id matcher-python正则表达式无法弄清楚

python - 并行运行两个嵌套的 for 循环以创建矩阵

javascript - 实时文档编辑和协作

html - 导航栏内的透明间隙

Python HTML 解析器分页