【问题标题】:Getting text from HTML using BeautifulSoup使用 BeautifulSoup 从 HTML 中获取文本
【发布时间】:2024-04-26 17:40:01
【问题描述】:

我正在尝试使用 Python2.7 和 BeautifulSoup4 从我的电力供应商的website 获取当前的“5 分钟趋势价格”。

xpath 是:xpath = "//html/body/div[2]/div/div/div[3]/p[1]"

<div class="instant prices">
  <p class="price">
    "5.2"  # this is what I'm ultimately after
    <small>¢</small>
    <strong> per kWh </strong>
  </p>

我尝试了无数不同的方法来获取 “5.2” 值,并成功地深入到“即时价格”对象,但无法从中获取任何信息.

我当前的代码如下所示: 导入 urllib2 从 bs4 导入 BeautifulSoup

url = "https://rrtp.comed.com/live-prices/"

soup = BeautifulSoup(urllib2.urlopen(url).read())
#print soup

instantPrices = soup.findAll('div', 'instant prices')
print instantPrices

...输出为:

[<div class="instant prices">
</div>]
[]

无论如何,“即时价格”对象似乎是空的,尽管我在 Chrome 中检查元素时可以清楚地看到它。 任何帮助将不胜感激!谢谢!

【问题讨论】:

    标签: html python-2.7 web-scraping beautifulsoup


    【解决方案1】:

    很遗憾,这些数据是在浏览器呈现网站时通过 Javascript 生成的。这就是为什么当您使用 urllib 下载源代码时没有此信息的原因。可以直接查询后端:

    >>> import urllib2
    >>> import re
    
    >>> url = "https://rrtp.comed.com/rrtp/ServletFeed?type=instant"
    >>> s = urllib2.urlopen(url).read()
    "<p class='price'>4.5<small>&cent;</small><strong> per kWh </strong></p><p>5-minute Trend Price 7:40 PM&nbsp;CT</p>\r\n"
    
    >>> float(re.findall("\d+.\d+", s)[0])
    4.5
    

    【讨论】:

    • 太棒了!谢谢你的回答,伊莱泽。工作正常。我显然还不太熟悉 HTML 或 JS。您是如何确定数据是由 JS 和后端 URL 生成的?
    • 例如,在 Chrome 中,您会看到“查看源代码”和“检查元素”之间的区别。源代码是您从服务器获得的,Inspect Element 还显示通过客户端浏览器上的 JavaScript 生成的内容。
    • 明白了。再次感谢。