python - lxml XPathposition() 不起作用

标签 python python-3.x xpath

我尝试通过 XPath 抓取页面,但无法使其按预期工作。

页面就像,

<tag1>
    <tag2>
          ....
              <div id=article>
                  <p> stuff1 </p>
                  <p> stuff2 </p>
                  <p> ...... </p>
                  <p> stuff30 </p>

我想将 stuff1stuff30 作为字符串提取。这是我的 Python 代码片段。

import lxml.html
import urllib.request

html = urllib.request.urlopen('http://www.something.com/news/blah/').read()
root = lxml.html.fromstring(html)

content = root.xpath('string(//div[@id="article"]/p[position()=>1 and position()<=last()]/.)')

此代码没有返回任何内容。

如果我将 position() 语句重写为单个元素索引,它就会起作用。

content = root.xpath('string(//div[@id="article"]/p[25]/.)')

此代码正确返回stuff25

我不想为此运行 for 循环。我相信有一种方法可以让我的代码与 position() 一起工作,但不确定我的代码出了什么问题。

最佳答案

那是因为你有position()=>1,应该是position()>=1

content = root.xpath('string(//div[@id="article"]/p[position()>=1 and position()<=last()]/.)')

将内容设置为 stuff1。

关于python - lxml XPathposition() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39242154/

相关文章:

python - 如何使用 Elasticsearch 和Python有效地索引json文件?

python - 在 Python 中是否有更简洁的方法来编写此 bool 比较?

c# - 如何使用C#将新的Counter属性添加到xml节点

python - 运行时错误 : DataLoader worker exited unexpectedly

Python - 确定ip是否是代理

python - 重新排列来自多个数据文件的数据

python - 运行 torchvision.utils.make_grid(images) 后死内核

python - 如何在 peewee 查询的文本字段中搜索子字符串

php - 使用 ZF 的 DOMElement 中的 Html

windows - 使用 XPath 选择与 Windows 事件日志中的其他条件不匹配的事件