选择器

现在我们用 Scrapy 官方提供的测试网址:" http://doc.scrapy.org/en/latest/_static/selectors-sample1.html " 为例,看看选择器的用法。

测试页面 HTML 代码如下:


 
  
  Example website
 
 
  
 

使用 Shell 来测试:

scrapy shell http://doc.scrapy.org/en/latest/_static/selectors-sample1.html

·


·

1.extract()方法

把被提取的内容转换为文本,输出一个列表。

>>> response.xpath('//title/text()').extract()
['Example website']

>>> response.css('img').xpath('@src').extract()
['image1_thumb.jpg',
 'image2_thumb.jpg',
 'image3_thumb.jpg',
 'image4_thumb.jpg',
 'image5_thumb.jpg']

如果只想获得被提取内容的第一个,可以使用 extract_first() 方法:

>>> response.css('img').xpath('@src').extract_first()
'image1_thumb.jpg'

判断提取内容内容是否存在,用 is None

>>> response.xpath('//div[@id="not-exists"]/text()').extract_first() is None
True

当提取内容不存在时,可以设定默认值。

>>> response.xpath('//div[@id="not-exists"]/text()').extract_first(default='not-found')
'not-found'

CSS 选择器可以使用 CSS3 伪元素来提取内容。

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

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

>>> response.css('a[href*=image]::attr(href)').extract()
['image1.html', 
'image2.html', 
'image3.html', 
'image4.html', 
'image5.html']
2.嵌套选择器

执行选择器方法后返回的选择器对象,可以继续对其使用选择器方法。

>>> links = response.css('#images')
>>> links.css('a > img::attr(src)').extract()
['image1_thumb.jpg', 
'image2_thumb.jpg', 
'image3_thumb.jpg', 
'image4_thumb.jpg', 
'image5_thumb.jpg']
3.使用正则表达式

直接使用 re() 方法即可。

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

extract_first() 方法类似,re_first() 返回用正则表达式提取的内容的第一项。

>>> response.xpath('//a[contains(@href, "image")]/text()').re_first(r'Name:\s*(.*)')
'My image 1 '

你可能感兴趣的:(选择器)