W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
當需要將文本內(nèi)容用作 XPath string function 避免使用 ?.//text()
? and use just ?.
? 相反。
這是因為表達式 ?.//text()
? 生成一個文本元素集合--a node-set . 當一個節(jié)點集被轉(zhuǎn)換成一個字符串時,當它作為參數(shù)傳遞給一個字符串函數(shù)(如 ?contains()
? 或 ?starts-with()
? ,它只為第一個元素生成文本。
例子:
>>> from scrapy import Selector
>>> sel = Selector(text='<a href="#">Click here to go to the <strong>Next Page</strong></a>')
轉(zhuǎn)換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 但是,轉(zhuǎn)換為字符串后,會將其自身的文本加上其所有后代的文本組合在一起:
>>> sel.xpath("http://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()
? 在這種情況下,節(jié)點集不會選擇任何內(nèi)容:
>>> sel.xpath("http://a[contains(.//text(), 'Next Page')]").getall()
[]
但是使用 ?.
? 指的是節(jié)點:
>>> sel.xpath("http://a[contains(., 'Next Page')]").getall()
['<a href="#">Click here to go to the <strong>Next Page</strong></a>']
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: