Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python lxml:正在分析html,无法获取节点_Python_Xpath_Lxml - Fatal编程技术网

Python lxml:正在分析html,无法获取节点

Python lxml:正在分析html,无法获取节点,python,xpath,lxml,Python,Xpath,Lxml,我正在尝试开始用lxml解析html。我从基本xpath知道,/应该选择根节点,//body应该选择位于dom中的body元素节点,等等。但是,我得到的所有节点的列表都是空的 from lxml import html import urllib2 headers = {'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0'} req = urllib2.Reque

我正在尝试开始用lxml解析html。我从基本xpath知道,
/
应该选择根节点,
//body
应该选择位于dom中的body元素节点,等等。但是,我得到的所有节点的列表都是空的

from lxml import html
import urllib2
headers =  {'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0'}
req = urllib2.Request("http://news.ycombinator.com", None, headers)
r = urllib2.urlopen(req).read()
x = html.fromstring(r)
x.xpath("/")
[]
编辑:

例如,这里是该页面的另一个有效xpath表达式,它返回一个空列表

x.xpath("/html/body/center/table/tbody/tr[3]/td/table/tbody/tr[1]/td[3]")
[] 
# when it should have returned the following (as of this time)
# <td class="title"><a href="http://www.tomdalling.com/blog/modern-opengl/opengl-in-2014/">OpenGL in 2014</a><span class="comhead"> (tomdalling.com) </span></td>
x.xpath(“/html/body/center/table/tbody/tr[3]/td/table/tbody/tr[1]/td[3]”)
[] 
#当它应该返回以下内容时(截至此时)
#(tomdalling.com)

关于第二个问题:xpath表达式的问题可能是tbody元素。 因为您已经可以在Stackoverflow上找到多个具有类似问题的问题-例如,此处和此处,简短版本 浏览器会向DOM中添加源代码中没有的元素,例如head和tbody, 因此xpath将不匹配。您可以省略tbody:

x.xpath("/html/body/center/table/tr[3]/td/table/tr[1]/td[3]")
正如这里所说的那样:

但我赞成第一个答案中给出的方法, -如果省略xpath中不必要的部分并将查询缩短为要查找的元素,那么它也应该可以工作,因此

x.xpath("/html/body/center/table/tbody/tr[3]/td/table/tbody/tr[1]/td[3]")
你应该用它来得到结果

x.xpath("/html/tr[3]/tr[1]/td[3]")   

你不知道这个urllib2.HTTPError:HTTP错误403:bankedenand[]做了什么吗?@Nabin-Oh,在实际代码中,我使用的是一个代理和一个假的用户代理,我没有发布。
[]
是最后第二行的输出。我将使这段代码可行,只需一分钟。@Nabin我已经更改了代码,
r
现在包含主页的html。在我的机器上测试过。可能是