Skip to main content
 首页 » 编程设计

python之lxml XPath position() 不起作用

2024年10月17日8sharpest

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

页面是这样的,

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

我想将 stuff1 到 stuff30 提取为字符串。这是我的 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。