【问题标题】:Python: why does the following xpath returns empty list?Python:为什么以下 xpath 返回空列表?
【发布时间】:2012-08-06 10:11:02
【问题描述】:

我正在尝试从instapaper.com 中提取一些文本和链接。所以我使用以下代码来完成工作:

>>> import lxml.html as lh
>>> doc = lh.parse("http://www.instapaper.com/u/folder/1227370/programming")
>>> text = doc.xpath(".//*[@id='bookmark_list']/*/div[3]/a/text()")
>>> len(text)
0
>>> text
[]

如您所见,它返回一个空列表,这意味着它无法找到与上述 xpath 匹配的任何文本。

现在,当我在 firebug/firepath 中使用上述 xpath expr 时,它工作正常。

您可以在上图中看到它显示40 matching nodes

所以,我的问题是为什么上面的 xpath 表达式不适用于 python/lxml。

根据要求Instapaper page source

【问题讨论】:

  • 尝试删除第一个句点字符。

标签: python xpath lxml


【解决方案1】:

没有 ID 为 bookmark_list 的元素。也许您必须登录。

编辑

解析 real HTML 它可以工作:

doc = lh.parse("http://pastebin.com/raw.php?i=1WpFAfCt")
text = doc.xpath("//*[@id='bookmark_list']/*/div[3]/a/text()")
len(text) # => 40

【讨论】:

  • 不错的收获。是的,我已登录。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多