selector的使用

安装parsel

pip install parsel

构造选择器

响应对象公开Selector实例对.selector属性:

>>> response.selector.xpath('//span/text()').get()
'good'

使用xpath和css查询响应非常常见,因此响应中还包含两个快捷方式:response.xpath()response.css()

>>> response.xpath('//span/text()').get()
'good'
>>> response.css('span::text').get()
'good'

使用选择器

为了完整起见,下面是完整的HTML代码:

<html>
 <head>
  <base href='http://example.com/' />
  <title>Example website</title>
 </head>
 <body>
  <div id='images'>
   <a href='image1.html'>Name: My image 1 <br /><img src='image1_thumb.jpg' /></a>
   <a href='image2.html'>Name: My image 2 <br /><img src='image2_thumb.jpg' /></a>
   <a href='image3.html'>Name: My image 3 <br /><img src='image3_thumb.jpg' /></a>
   <a href='image4.html'>Name: My image 4 <br /><img src='image4_thumb.jpg' /></a>
   <a href='image5.html'>Name: My image 5 <br /><img src='image5_thumb.jpg' /></a>
  </div>
 </body>
</html>

通过观察 HTML code 对于该页面,让我们构造一个用于选择标题标记内文本的xpath

>>> response.xpath('//title/text()')
[<Selector xpath='//title/text()' data='Example website'>]

要实际提取文本数据,必须调用选择器.get().getall()方法如下:

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

.get()始终返回单个结果;如果有多个匹配项,则返回第一个匹配项的内容;
如果没有匹配项,则不返回任何匹配项。.getall()返回包含所有结果的列表。

css选择器可以使用css3伪元素选择文本或属性节点:

>>> response.css('title::text').get()
'Example website'

.xpath().css()方法可用于快速选择嵌套数据

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

只提取第一个匹配的元素,则可以调用选择器.get()(或其别名).extract_first()

>>> response.xpath('//div[@id="images"]/a/text()').get()
'Name: My image 1 '

如果未找到元素,返回None

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

可以将默认返回值作为参数提供,以代替None

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

参考:
https://pypi.org/project/parsel/
https://www.osgeo.cn/scrapy/topics/selectors.html

posted @ 2020-05-25 09:57  hank-li  阅读(367)  评论(0编辑  收藏  举报