阅读(3925) (0)

scrapy 2.3 在条件中使用文本节点

2021-06-03 14:26:14 更新

当需要将文本内容用作 XPath string function 避免使用 ​.//text()​ and use just ​.​ 相反。

这是因为表达式 ​.//text()​ 生成一个文本元素集合--a node-set . 当一个节点集被转换成一个字符串时,当它作为参数传递给一个字符串函数(如 ​contains()​ 或 ​starts-with()​ ,它只为第一个元素生成文本。

例子:

>>> from scrapy import Selector
>>> sel = Selector(text='<a href="#">Click here to go to the <strong>Next Page</strong></a>')

转换A node-set 字符串:

>>> sel.xpath('//a//text()').getall() # take a peek at the node-set
['Click here to go to the ', 'Next Page']
>>> sel.xpath("string(//a[1]//text())").getall() # convert it to string
['Click here to go to the ']

A node 但是,转换为字符串后,会将其自身的文本加上其所有后代的文本组合在一起:

>>> sel.xpath("//a[1]").getall() # select the first node
['<a href="#">Click here to go to the <strong>Next Page</strong></a>']
>>> sel.xpath("string(//a[1])").getall() # convert it to string
['Click here to go to the Next Page']

所以,使用 ​.//text()​ 在这种情况下,节点集不会选择任何内容:

>>> sel.xpath("//a[contains(.//text(), 'Next Page')]").getall()
[]

但是使用 ​.​ 指的是节点:

>>> sel.xpath("//a[contains(., 'Next Page')]").getall()
['<a href="#">Click here to go to the <strong>Next Page</strong></a>']