如果您可以依赖 'Latest Price' 标记内的字符串 <strong>,那么您可以使用:
In [305]: root.xpath('//strong[contains(text(), "Latest Price:")]/text()')
Out[305]: ['Latest Price: 34']
或者,也许更可靠的是,您可以搜索所有 <p> 标签及其后代以查找包含字符串 'Latest Price' 的文本:
In [312]: root.xpath('//p/descendant-or-self::*[contains(text(), "Latest Price")]/text()')
Out[312]: ['Latest Price: 34']
import urllib2
url = 'https://www.predictit.org/Contract/838/'
page = urllib2.urlopen(url)
data = page.read()
import lxml.html as LH
root = LH.fromstring(data)
price = None
for text in root.xpath('//p/descendant-or-self::*[contains(text(), "Latest Price:")]/text()'):
price = float(text.split(':', 1)[-1])
print(price)
# 35
XPath /html/body/div[7]/div/div[2]/div[2]/p[1]/strong/text() 可能失败的原因是因为从 urllib2.urlopen(url).read() 收到的 HTML 可能与 Chrome 收到的 HTML 不同。 Chrome 的浏览器会处理可能会更改 DOM 的 JavaScript。 urllib2 不处理 JavaScript。如果您在执行 JavaScript 后需要 DOM,那么您将需要像 Selenium 这样的自动化浏览器,而不是 urllib2。幸运的是,在这种情况下,您要查找的内容不是由 JavaScript 提供的。但是,过于具体的 XPath(例如 /html/body/div[7]/div/div[2]/div[2]/p[1]/strong/text())可能会让您失望。
使用urllib2返回的HTML,似乎只有6个<div>标签:
In [315]: root.xpath('/html/body/div')
Out[315]:
[<Element div at 0x7f0bd63632b8>,
<Element div at 0x7f0bd6363310>,
<Element div at 0x7f0bd6363368>,
<Element div at 0x7f0bd63633c0>,
<Element div at 0x7f0bd6363418>,
<Element div at 0x7f0bd6363470>]
尝试访问第 7 个 <div> 标记会产生一个空列表:
In [316]: root.xpath('/html/body/div[7]')
Out[316]: []