Python lxml XPath问题

发布于 2024-10-22 21:25:12 字数 715 浏览 5 评论 0原文

我正在尝试从网页打印/保存某个元素的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

榕城若虚 2024-10-29 21:25:12

您的 XPath 显然有点太长了,为什么不尝试较短的 XPath 并看看它们是否匹配。一个问题可能是“tbody”,它由浏览器在 DOM 中自动创建,但 HTML 标记通常不包含它。

以下是如何使用 XPath 结果的示例:

>>> from lxml import etree
>>> from StringIO import StringIO
>>> doc = etree.parse(StringIO("<html><body>a<something/>b</body></root>"), etree.HTMLParser())
>>> doc.xpath("/html/body/text()")
['a', 'b']

因此,如果需要,您可以将所有文本部分 "".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:

>>> from lxml import etree
>>> from StringIO import StringIO
>>> doc = etree.parse(StringIO("<html><body>a<something/>b</body></root>"), etree.HTMLParser())
>>> doc.xpath("/html/body/text()")
['a', 'b']

So you could just "".join(...) all text parts together if needed.

暮光沉寂 2024-10-29 21:25:12

不确定我完全遵循你想要完成的目标,但最终我认为你正在寻找:

print etree.tostring(elem[0])

Not sure I completely follow what you are trying to accomplish, but ultimately I think you are looking for:

print etree.tostring(elem[0])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文