【发布时间】:2021-12-18 14:15:18
【问题描述】:
什么是正确的语法:
//footer//a | (//a[not(//footer)] and position() <=200)
如果存在则仅使用 //footer,如果不存在,则查找所有不在 //footer 中的 //a 并将其限制为 200
【问题讨论】:
标签: python python-3.x web-scraping xpath scrapy
什么是正确的语法:
//footer//a | (//a[not(//footer)] and position() <=200)
如果存在则仅使用 //footer,如果不存在,则查找所有不在 //footer 中的 //a 并将其限制为 200
【问题讨论】:
标签: python python-3.x web-scraping xpath scrapy
你真的很亲密。 OR 运算符已经处理了您的情况 - 如果页脚下面不包含 <a> 节点,则将捕获第二个 OR 语句:
使用python 和parsel(scrapy 的 html 解析器)。
>>> foo = Selector("<footer><a>text</a></footer>")
>>> bar = Selector("<div><a>text</a><a>text2</a><a>text3</a><a>text4</a></div>")
>>> foo.xpath("//footer//a | //a[position()<=2]").get()
'<a>text</a>'
>>> bar.xpath("//footer//a | //a[position()<=2]").extract()
['<a>text</a>', '<a>text2</a>']
注意:为简洁起见,我使用了2 而不是200。
【讨论】: