Python lxml XPath问题
我正在尝试从网页打印/保存某个元素的 HTML。
我已经从 firebug 检索了请求元素的 XPath。
我所希望的只是将此元素保存到文件中。 我似乎没有成功这样做。
(最后尝试了带或不带 /text()
的 XPath)
我将不胜感激任何帮助或过去的经验。
10x,大卫
import urllib2,StringIO
from lxml import etree
url='http://www.tutiempo.net/en/Climate/Londres_Heathrow_Airport/12-2009/37720.htm'
seite = urllib2.urlopen(url)
html = seite.read()
seite.close()
parser = etree.HTMLParser()
tree = etree.parse(StringIO.StringIO(html), parser)
xpath = "/html/body/table/tbody/tr/td[2]/div/table/tbody/tr[6]/td/table/tbody/tr/td[3]/table/tbody/tr[3]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/text()"
elem = tree.xpath(xpath)
print elem[0].strip().encode("utf-8")
I'm trying to print/save a certain element's HTML from a web-page.
I've retrieved the requested element's XPath from firebug.
All I wish is to save this element to a file.
I don't seem to succeed in doing so.
(tried the XPath with and without a /text()
at the end)
I would appreciate any help, or past experience.
10x, David
import urllib2,StringIO
from lxml import etree
url='http://www.tutiempo.net/en/Climate/Londres_Heathrow_Airport/12-2009/37720.htm'
seite = urllib2.urlopen(url)
html = seite.read()
seite.close()
parser = etree.HTMLParser()
tree = etree.parse(StringIO.StringIO(html), parser)
xpath = "/html/body/table/tbody/tr/td[2]/div/table/tbody/tr[6]/td/table/tbody/tr/td[3]/table/tbody/tr[3]/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/text()"
elem = tree.xpath(xpath)
print elem[0].strip().encode("utf-8")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 XPath 显然有点太长了,为什么不尝试较短的 XPath 并看看它们是否匹配。一个问题可能是“tbody”,它由浏览器在 DOM 中自动创建,但 HTML 标记通常不包含它。
以下是如何使用 XPath 结果的示例:
因此,如果需要,您可以将所有文本部分
"".join(...)
组合在一起。Your XPath is obviously a bit too long, why don't you try shorter ones and see if they match. One problem might be "tbody" which gets automatically created in the DOM by browsers but the HTML markup usually does not contain it.
Here's an example of how to use XPath results:
So you could just
"".join(...)
all text parts together if needed.不确定我完全遵循你想要完成的目标,但最终我认为你正在寻找:
Not sure I completely follow what you are trying to accomplish, but ultimately I think you are looking for: