2

我正在尝试使用 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”的价值,并成功地深入到“即时价格”对象,但无法从中得到任何东西。

我当前的代码如下所示: import urllib2 from bs4 import 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 中检查元素时可以清楚地看到它。任何帮助将不胜感激!谢谢!

4

1 回答 1

2

不幸的是,当浏览器呈现网站时,这些数据是通过 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
于 2013-09-10T00:40:03.810 回答