我尝试通过 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。
关于python - lxml XPathposition() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39242154/