對於要提取嵌套標簽所有內容的情況, 使用string
或//text()
, 注意兩者區別
>>> from scrapy import Selector
>>>
>>> doc = "<p id='test'>hello<b>world!</b></p>"
>>>
>>> sel = Selector(text=doc, type='html')
>>>
>>> sel.xpath("/p[@id='test']/text()").extract()
[]
使用text()
>>>#使用兩個反斜杠
>>> sel.xpath("//p[@id='test']/text()").extract()
[u'hello']
>>> #這樣提取出來是一個列表,
>>> sel.xpath("//p[@id='test']//text()").extract()
[u'hello', u'world!']
>>>
使用string
>>> sel.xpath("//p[@id='test']").xpath('string(.)').extract()
[u'helloworld!']
>>>
>>> sel.xpath("string(//p[@id='test'])").extract()
[u'helloworld!']
>>>