Scrapy提取数据有自己的一套机制,被称作选择器(selectors),通过特定的Xpath或者CSS表达式来选择HTML文件的某个部分
Xpath是专门在XML文件中选择节点的语言,也可以用在HTML上。
CSS是一门将HTML文档样式化语言,选择器由它定义,并与特定的HTML元素的样式相关联。

XPath选择器

常用的路径表达式,这里列举了一些常用的,XPath的功能非常强大,内含超过100个的内建函数。
下面为常用的方法

nodeName    选取此节点的所有节点
/ 从根节点选取
// 从匹配选择的当前节点选择文档中的节点,不考虑它们的位置
. 选择当前节点
.. 选取当前节点的父节点
@ 选取属性
* 匹配任何元素节点
@* 匹配任何属性节点
Node() 匹配任何类型的节点

CSS选择器

CSS层叠样式表,语法由两个主要部分组成:选择器,一条或多条声明
Selector {declaration1;declaration2;……}

下面为常用的使用方法

.class              .color              选择class=”color”的所有元素
#id #info 选择id=”info”的所有元素
* * 选择所有元素
element p 选择所有的p元素
element,element div,p 选择所有div元素和所有p元素
element element div p 选择div标签内部的所有p元素
[attribute] [target] 选择带有targe属性的所有元素
[arrtibute=value] [target=_blank] 选择target=”_blank”的所有元素

选择器的使用例子

上面我们列举了两种选择器的常用方法,下面通过scrapy帮助文档提供的一个地址来做演示
地址:http://doc.scrapy.org/en/latest/_static/selectors-sample1.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>

我们通过scrapy shell http://doc.scrapy.org/en/latest/_static/selectors-sample1.html来演示两种选择器的功能

获取title

这里的extract_first()就可以获取title标签的文本内容,因为我们第一个通过xpath返回的结果是一个列表,所以我们通过extract()之后返回的也是一个列表,而extract_first()可以直接返回第一个值,extract_first()有一个参数default,例如:extract_first(default="")表示如果匹配不到返回一个空

In [1]: response.xpath('//title/text()')
Out[1]: [<Selector xpath='//title/text()' data='Example website'>] In [2]: response.xpath('//title/text()').extract_first()
Out[2]: 'Example website' In [6]: response.xpath('//title/text()').extract()
Out[6]: ['Example website']

同样的我们也可以通过css选择器获取,例子如下:

In [7]: response.css('title::text')
Out[7]: [<Selector xpath='descendant-or-self::title/text()' data='Example website'>] In [8]: response.css('title::text').extract_first()
Out[8]: 'Example website'

查找图片信息
这里通过xpath和css结合使用获取图片的src地址:

In [13]: response.xpath('//div[@id="images"]').css('img')
Out[13]:
[<Selector xpath='descendant-or-self::img' data='<img src="data:image1_thumb.jpg">'>,
<Selector xpath='descendant-or-self::img' data='<img src="data:image2_thumb.jpg">'>,
<Selector xpath='descendant-or-self::img' data='<img src="data:image3_thumb.jpg">'>,
<Selector xpath='descendant-or-self::img' data='<img src="data:image4_thumb.jpg">'>,
<Selector xpath='descendant-or-self::img' data='<img src="data:image5_thumb.jpg">'>] In [14]: response.xpath('//div[@id="images"]').css('img::attr(src)').extract()
Out[14]:
['image1_thumb.jpg',
'image2_thumb.jpg',
'image3_thumb.jpg',
'image4_thumb.jpg',
'image5_thumb.jpg']

查找a标签信息
这里分别通过xapth和css选择器获取a标签的href内容,以及文本信息,css获取属性信息是通过attr,xpath是通过@属性名

In [15]: response.xpath('//a/@href')
Out[15]:
[<Selector xpath='//a/@href' data='image1.html'>,
<Selector xpath='//a/@href' data='image2.html'>,
<Selector xpath='//a/@href' data='image3.html'>,
<Selector xpath='//a/@href' data='image4.html'>,
<Selector xpath='//a/@href' data='image5.html'>] In [16]: response.xpath('//a/@href').extract()
Out[16]: ['image1.html', 'image2.html', 'image3.html', 'image4.html', 'image5.html'] In [17]: response.css('a::attr(href)')
Out[17]:
[<Selector xpath='descendant-or-self::a/@href' data='image1.html'>,
<Selector xpath='descendant-or-self::a/@href' data='image2.html'>,
<Selector xpath='descendant-or-self::a/@href' data='image3.html'>,
<Selector xpath='descendant-or-self::a/@href' data='image4.html'>,
<Selector xpath='descendant-or-self::a/@href' data='image5.html'>] In [18]: response.css('a::attr(href)').extract()
Out[18]: ['image1.html', 'image2.html', 'image3.html', 'image4.html', 'image5.html'] In [27]: response.css('a::text').extract()
Out[27]:
['Name: My image 1 ',
'Name: My image 2 ',
'Name: My image 3 ',
'Name: My image 4 ',
'Name: My image 5 '] In [28]: response.xpath('//a/text()').extract()
Out[28]:
['Name: My image 1 ',
'Name: My image 2 ',
'Name: My image 3 ',
'Name: My image 4 ',
'Name: My image 5 '] In [29]:

高级用法
查找属性名称包含img的所有的超链接,通过contains实现

In [36]: response.xpath('//a[contains(@href,"image")]/@href').extract()
Out[36]: ['image1.html', 'image2.html', 'image3.html', 'image4.html', 'image5.html'] In [37]: response.css('a[href*=image]::attr(href)').extract()
Out[37]: ['image1.html', 'image2.html', 'image3.html', 'image4.html', 'image5.html'] In [38]:

查找img的src属性

In [41]: response.xpath('//a[contains(@href,"image")]/img/@src').extract()
Out[41]:
['image1_thumb.jpg',
'image2_thumb.jpg',
'image3_thumb.jpg',
'image4_thumb.jpg',
'image5_thumb.jpg'] In [42]: response.css('a[href*=image] img::attr(src)').extract()
Out[42]:
['image1_thumb.jpg',
'image2_thumb.jpg',
'image3_thumb.jpg',
'image4_thumb.jpg',
'image5_thumb.jpg'] In [43]:

提取a标签的文本中name后面的内容,这里提供了正则的方法re和re_first

In [43]: response.css('a::text').re('Name\:(.*)')
Out[43]:
[' My image 1 ',
' My image 2 ',
' My image 3 ',
' My image 4 ',
' My image 5 '] In [44]: response.css('a::text').re_first('Name\:(.*)')
Out[44]: ' My image 1 '

爬虫(十一):scrapy中的选择器的更多相关文章

  1. 使用scrapy中xpath选择器的一个坑点

    情景如下: 一个网页下有一个ul,这个ur下有125个li标签,每个li标签下有我们想要的 url 字段(每个 url 是唯一的)和 price 字段,我们现在要访问每个li下的url并在生成的请求中 ...

  2. 第三百二十五节,web爬虫,scrapy模块标签选择器下载图片,以及正则匹配标签

    第三百二十五节,web爬虫,scrapy模块标签选择器下载图片,以及正则匹配标签 标签选择器对象 HtmlXPathSelector()创建标签选择器对象,参数接收response回调的html对象需 ...

  3. 四 web爬虫,scrapy模块标签选择器下载图片,以及正则匹配标签

    标签选择器对象 HtmlXPathSelector()创建标签选择器对象,参数接收response回调的html对象需要导入模块:from scrapy.selector import HtmlXPa ...

  4. 爬虫(scrapy中的ImagesPipeline)

    在使用ImagesPipeline对妹子图网站图片进行下载时,遇到302错误,页面被强制跳转. 解决办法如下: # -*- coding: utf-8 -*- # Define your item p ...

  5. 爬虫(scrapy中调试文件)

    在项目setting同级目录下创建py文件,代码如下: from scrapy.cmdline import execute import sys import os sys.path.append( ...

  6. scrapy中css选择器初识

    由于最近做图片爬取项目,涉及到网页中图片信息的选择,所以边做边学了点皮毛,有自己的心得 百度图库是ajax加载的,所以解析json数据即可 hjsons = json.loads(response.b ...

  7. 第三百五十一节,Python分布式爬虫打造搜索引擎Scrapy精讲—将selenium操作谷歌浏览器集成到scrapy中

    第三百五十一节,Python分布式爬虫打造搜索引擎Scrapy精讲—将selenium操作谷歌浏览器集成到scrapy中 1.爬虫文件 dispatcher.connect()信号分发器,第一个参数信 ...

  8. 教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神

    本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http://www.xiaohuar.com/,让你体验爬取校花的成就感. Scr ...

  9. 【转载】教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神

    原文:教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神 本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http:/ ...

随机推荐

  1. sidecar-inject代码分析

    Istio通过对serviceMesh中的每个pod注入sidecar,来实现无侵入式的服务治理能力.其中,sidecar的注入是其能力实现的重要一环(本文主要介绍在kubernetes集群中的注入方 ...

  2. Kettle部署笔记

    1.启动脚本(启动job) /u02/www/data-integration/kitchen.sh -file:/u02/www/data-integration/job.kjb -logfile= ...

  3. Neo4J之标签类型

    Neo4J的标签可以理解一个类,在创建一个节点时可以设置一个或多个标签: 1. 标签名为中文(可以) CRATE(节点名:标签1:标签2{属性1:34} 创建了一个节点名为“节点名”的节点(不可以用节 ...

  4. 【转载】网站配置Https证书系列(二):IIS服务器给网站配置Https证书

    针对网站的Https证书,即SSL证书,腾讯云.阿里云都提供了免费的SSL证书申请,SSL证书申请下来后,就需要将SSL证书配置到网站中,如果网站使用的Web服务器是IIS服务器,则需要在IIS服务器 ...

  5. orangepi香橙派安装VNC Viewer远程桌面

    用ssh连接实在没有图形界面操作的好,虽然命令会快,但是很多命令都记不住. 第一步: sudo apt-get install xfce4 第二步: sudo apt-get install vnc4 ...

  6. Xcode11.1 踩坑备忘录

    Xcode11.1 踩坑备忘录(mac系统10.15) 1 .环信ChatDemo2.0报错 这是环信ChatDemo2.0报错 NSInteger numberOfBeforeSection = [ ...

  7. django_rest framework 接口开发(一)

    1 restful 规范(建议) 基于FbV def order(request): if request.method=="GET": return HttpResponse(' ...

  8. ubuntu 中安装sublime-text3

    ubuntu 中安装sublime_text3Enter "Alt+m" will show Markdown Preview 安装 输入注册码 汉化 安装插件 中文输入bug修复 ...

  9. Linux常用命令【1】

    打包和压缩文件 : cd /home 进入 '/ home' 目录' cd .. 返回上一级目录 cd ../.. 返回上两级目录 cd 进入个人的主目录 cd ~user1 进入个人的主目录 cd ...

  10. 模仿DotnetCore中间件的方式,做一个列表过滤的功能

    我们的很多功能当中都会遇到对版本进行过滤的场合,例如你可能需要对列表中的数据的时间进行过滤.版本过滤.渠道以及地区信息进行过滤. 原本的做法:设计很多个过滤方法,通过枚举的方式组合,选择需要过滤哪些方 ...