我正在尝试将 lxml 与 python 一起使用,因为在阅读并执行谷歌建议后,将 lxml 用于其他解析包。我有以下 dom 结构,我管理编写正确的 xpath,我在 xpath 检查中仔细检查我的 xpath 以确认它的有效性。Xpath 在 Xpath Checker 上运行良好,但是当我将它与 python 中的 lxml 一起使用时,我没有得到结果,我得到的是对象而不是实际的文本。
这是我的dom结构:
<div class="pdsc-l">
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<tr>
<tr>
<tr>
<tr>
<tr>
<td width="35%" valign="top">
<font size="2" face="Arial, Helvetica, sans-serif">Brand</font>
</td>
<td width="65%" valign="top">
<font size="2" face="Arial, Helvetica, sans-serif">HTC</font>
</td>
</tr>
<tr>
<td width="35%" valign="top">
<td width="65%" valign="top">
遵循我写的 xpath 给了我我想要的东西..
//td//font[text()='Brand']/following::td[1]
但是使用 lxml 我不会得到结果:
This is my code:
rawPage = urllib2.urlopen(request)
read = rawPage.read()
#print read
tree = etree.HTML(read)
for tr in tree.xpath("//tr"):
print tr.xpath("//td//font[text()='Brand']/following::td[1]")
这是输出
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
[<Element td at 0x10ad80b90>]
我尝试了以下更改,但仍然没有得到结果,我编写的代码有 url,希望这将有助于获得更好的答案:
from lxml import etree
from lxml.html import fromstring, tostring
url = 'http://www.ebay.com/ctg/111176858'
request = urllib2.Request(url)
rawPage = urllib2.urlopen(request)
read = rawPage.read()
#print read
tree = etree.HTML(read)
for tr in tree.xpath("//tr"):
t = tr.xpath("//td//font[text()='Brand']/following::td[1]")[0]
print tostring(t)