使用lxml和xpath从网页中获取文本

2024-05-23 19:09:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个网页上找出一个数字,特别是目前的总统支持率来自RealClearPolitics。在

下面是我使用的代码,尝试使用urllib2获取网页,lxml解析它,并使用chrome报告的xpath。问题是,我最后得到的只是一张空名单。在

import urllib2
from lxml import etree

url = "http://www.realclearpolitics.com/epolls/other/president_obama_job_approval-1044.html"
page = urllib2.urlopen(url)

tree = etree.parse(page.content, etree.HTMLParser())

rcp=tree.xpath('//*[@id="polling-data-rcp"]/table/tbody/tr[2]/td[4]')

print rcp

任何帮助都将不胜感激!在


Tags: 代码importtreeurl网页page数字urllib2
1条回答
网友
1楼 · 发布于 2024-05-23 19:09:21

tr[2]/td[4]不对。参见:

enter image description here

因此您需要使用正确的XPath查询:

enter image description here

Python代码是:

import requests
from lxml import html

URL = "http://www.realclearpolitics.com/epolls/other/president_obama_job_approval-1044.html"
response = requests.get(URL)
tree = html.fromstring(response.content)

rcp_approve = '//table[@class="chart_legend small_legend"]/tbody/tr/td[@class="candidate"][1]/div[1]/span/text()'
rcp_disapprove = '//table[@class="chart_legend small_legend"]/tbody/tr/td[@class="candidate"][2]/div[1]/span/text()'

rcp_approve = float(tree.xpath(rcp_approve)[0])
rcp_disapprove = float(tree.xpath(rcp_disapprove)[0])

print "Obama's approve rate: {}".format(rcp_approve)
print "Obama's disapprove rate: {}".format(rcp_disapprove)

输出:

^{pr2}$

相关问题 更多 >