Scrapy提取多个标签的text

对于要提取嵌套标签所有内容的情况, 使用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!']
>>> 

猜你喜欢

转载自blog.csdn.net/feifly329/article/details/86076246