天天看點

Scrapy選擇器的用法

1.構造選擇器:

>>> response = HtmlResponse(url='http://example.com', body=body)
>>> Selector(response=response).xpath('//span/text()').extract()
[u'good']      

2.使用選擇器(在response使用xpath或CSS查詢):

.xpath()

 及 

.css()

 方法傳回一個類 

SelectorList

 的執行個體, 它是一個新選擇器的清單。

>>> response.xpath('//title/text()')
[<Selector (text) xpath=//title/text()>]
>>> response.css('title::text')
[<Selector (text) xpath=//title/text()>]      

xpath中 //選取标簽,/選擇屬性, CSS中用 :: 選取屬性。

調用 extract() 來擷取标簽内容,使用extract_frist()來擷取第一個元素内容。

>>> response.css('title::text').extract()
[u'Example website']      

使用@或attr()來擷取屬性。

>>> response.xpath('//base/@href').extract()
[u'http://example.com/']

>>> response.css('base::attr(href)').extract()
[u'http://example.com/']      

擷取指定内容,如image。

>>> response.xpath('//a[contains(@href, "image")]/@href').extract()
[u'image1.html',
 u'image2.html',
 u'image3.html',
 u'image4.html',
 u'image5.html']

>>> response.css('a[href*=image]::attr(href)').extract()
[u'image1.html',
 u'image2.html',
 u'image3.html',
 u'image4.html',
 u'image5.html']      

結合正規表達式。

>>> response.xpath('//a[contains(@href, "image")]/text()').re(r'Name:\s*(.*)')
[u'My image 1',
 u'My image 2',
 u'My image 3',
 u'My image 4',
 u'My image 5']