我正在尝试从 website 获取当前的“5 分钟趋势价格”我的电力供应商使用 Python2.7 和 BeautifulSoup4。
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 中检查该元素时可以清楚地看到它。 任何帮助将不胜感激!谢谢!
最佳答案
不幸的是,这些数据是在浏览器呈现网站时通过 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>¢</small><strong> per kWh </strong></p><p>5-minute Trend Price 7:40 PM CT</p>\r\n"
>>> float(re.findall("\d+.\d+", s)[0])
4.5
关于html - 使用 BeautifulSoup 从 HTML 获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18709006/