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