我正在尝试使用Python2.7和BeautifulSoup4从电力提供商的网站上获取当前的“ 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”值,并且成功地钻取了“即时价格”对象,但无法从中获得任何收益。
我当前的代码如下所示:从bs4导入urllib2导入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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句