标签选择器对象

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

select()标签选择器方法,是HtmlXPathSelector里的一个方法,参数接收选择器规则,返回列表元素是一个标签对象

extract()获取到选择器过滤后的内容,返回列表元素是内容

选择器规则

  //x 表示向下查找n层指定标签,如://div 表示查找所有div标签
  /x 表示向下查找一层指定的标签
  /@x 表示查找指定属性,可以连缀如:@id @src
  [@class="class名称"] 表示查找指定属性等于指定值的标签,可以连缀 ,查找class名称等于指定名称的标签
  /text() 获取标签文本类容
  [x] 通过索引获取集合里的指定一个元素

获取指定的标签对象

# -*- coding: utf-8 -*-
import scrapy #导入爬虫模块
from scrapy.selector import HtmlXPathSelector #导入HtmlXPathSelector模块
from urllib import request #导入request模块
import os class AdcSpider(scrapy.Spider):
name = 'adc' #设置爬虫名称
allowed_domains = ['www.shaimn.com']
start_urls = ['http://www.shaimn.com/xinggan/'] def parse(self, response):
hxs = HtmlXPathSelector(response) #创建HtmlXPathSelector对象,将页面返回对象传进去 items = hxs.select('//div[@class="showlist"]/li') #标签选择器,表示获取所有class等于showlist的div,下面的li标签
print(items) #返回标签对象

循环获取到每个li标签里的子标签,以及各种属性或者文本

# -*- coding: utf-8 -*-
import scrapy #导入爬虫模块
from scrapy.selector import HtmlXPathSelector #导入HtmlXPathSelector模块
from urllib import request #导入request模块
import os class AdcSpider(scrapy.Spider):
name = 'adc' #设置爬虫名称
allowed_domains = ['www.shaimn.com']
start_urls = ['http://www.shaimn.com/xinggan/'] def parse(self, response):
hxs = HtmlXPathSelector(response) #创建HtmlXPathSelector对象,将页面返回对象传进去 items = hxs.select('//div[@class="showlist"]/li') #标签选择器,表示获取所有class等于showlist的div,下面的li标签
# print(items) #返回标签对象
for i in range(len(items)): #根据li标签的长度循环次数
title = hxs.select('//div[@class="showlist"]/li[%d]//img/@alt' % i).extract() #根据循环的次数作为下标获取到当前li标签,下的img标签的alt属性内容
src = hxs.select('//div[@class="showlist"]/li[%d]//img/@src' % i).extract() #根据循环的次数作为下标获取到当前li标签,下的img标签的src属性内容
if title and src:
print(title,src) #返回类容列表

将获取到的图片下载到本地

urlretrieve()将文件保存到本地,参数1要保存文件的src,参数2保存路径
urlretrieve是urllib下request模块的一个方法,需要导入from urllib import request

# -*- coding: utf-8 -*-
import scrapy #导入爬虫模块
from scrapy.selector import HtmlXPathSelector #导入HtmlXPathSelector模块
from urllib import request #导入request模块
import os class AdcSpider(scrapy.Spider):
name = 'adc' #设置爬虫名称
allowed_domains = ['www.shaimn.com']
start_urls = ['http://www.shaimn.com/xinggan/'] def parse(self, response):
hxs = HtmlXPathSelector(response) #创建HtmlXPathSelector对象,将页面返回对象传进去 items = hxs.select('//div[@class="showlist"]/li') #标签选择器,表示获取所有class等于showlist的div,下面的li标签
# print(items) #返回标签对象
for i in range(len(items)): #根据li标签的长度循环次数
title = hxs.select('//div[@class="showlist"]/li[%d]//img/@alt' % i).extract() #根据循环的次数作为下标获取到当前li标签,下的img标签的alt属性内容
src = hxs.select('//div[@class="showlist"]/li[%d]//img/@src' % i).extract() #根据循环的次数作为下标获取到当前li标签,下的img标签的src属性内容
if title and src:
# print(title[0],src[0]) #通过下标获取到字符串内容
file_path = os.path.join(os.getcwd() + '/img/', title[0] + '.jpg') #拼接图片保存路径
request.urlretrieve(src[0], file_path) #将图片保存到本地,参数1获取到的src,参数2保存路径

xpath()标签选择器,是Selector类里的一个方法,参数是选择规则【推荐】

选择器规则同上

selector()创建选择器类,需要接受html对象
需要导入:from scrapy.selector import Selector

# -*- coding: utf-8 -*-
import scrapy #导入爬虫模块
from scrapy.selector import HtmlXPathSelector #导入HtmlXPathSelector模块
from scrapy.selector import Selector class AdcSpider(scrapy.Spider):
name = 'adc' #设置爬虫名称
allowed_domains = ['www.shaimn.com']
start_urls = ['http://www.shaimn.com/xinggan/'] def parse(self, response):
items = Selector(response=response).xpath('//div[@class="showlist"]/li').extract()
# print(items) #返回标签对象
for i in range(len(items)):
title = Selector(response=response).xpath('//div[@class="showlist"]/li[%d]//img/@alt' % i).extract()
src = Selector(response=response).xpath('//div[@class="showlist"]/li[%d]//img/@src' % i).extract()
print(title,src)

正则表达式的应用

正则表达式是弥补,选择器规则无法满足过滤情况时使用的,

分为两种正则使用方式

  1、将选择器规则过滤出来的结果进行正则匹配

  2、在选择器规则里应用正则进行过滤

1、将选择器规则过滤出来的结果进行正则匹配,用正则取最终内容

最后.re('正则')

# -*- coding: utf-8 -*-
import scrapy #导入爬虫模块
from scrapy.selector import HtmlXPathSelector #导入HtmlXPathSelector模块
from scrapy.selector import Selector class AdcSpider(scrapy.Spider):
name = 'adc' #设置爬虫名称
allowed_domains = ['www.shaimn.com']
start_urls = ['http://www.shaimn.com/xinggan/'] def parse(self, response):
items = Selector(response=response).xpath('//div[@class="showlist"]/li//img')[0].extract()
print(items) #返回标签对象
items2 = Selector(response=response).xpath('//div[@class="showlist"]/li//img')[0].re('alt="(\w+)')
print(items2) # <img src="http://www.shaimn.com/uploads/170724/1-1FH4221056141.jpg" alt="人体艺术mmSunny前凸后翘性感诱惑写真">
# ['人体艺术mmSunny前凸后翘性感诱惑写真']

2、在选择器规则里应用正则进行过滤

[re:正则规则]

# -*- coding: utf-8 -*-
import scrapy #导入爬虫模块
from scrapy.selector import HtmlXPathSelector #导入HtmlXPathSelector模块
from scrapy.selector import Selector class AdcSpider(scrapy.Spider):
name = 'adc' #设置爬虫名称
allowed_domains = ['www.shaimn.com']
start_urls = ['http://www.shaimn.com/xinggan/'] def parse(self, response):
items = Selector(response=response).xpath('//div').extract()
# print(items) #返回标签对象
items2 = Selector(response=response).xpath('//div[re:test(@class, "showlist")]').extract() #正则找到div的class等于showlist的元素
print(items2)

四 web爬虫,scrapy模块标签选择器下载图片,以及正则匹配标签的更多相关文章

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

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

  2. 爬虫scrapy模块

    首先下载scrapy模块 这里有惊喜 https://www.cnblogs.com/bobo-zhang/p/10068997.html 创建一个scrapy文件 首先在终端找到一个文件夹 输入 s ...

  3. scrapy中的ImagePipeline下载图片到本地、并提取本地的保存地址

    通过scrapy内置到ImagePipeline下载图片到本地 在settings中打开 ITEM_PIPELINES的注释,并在这里面加入 'scrapy.pipelines.images.Imag ...

  4. 使用a标签直接下载图片

    通常情况下,使用a标签链接到图片,会在浏览器中打开这个图片,而不会下载 如果要直接下载这个图片,可以使用download属性配合href属性 <a href="./1.jpg" ...

  5. 在html使用a标签 直接下载图片 不通过后台实现直接下载

    由于a标签在HTML中链接图片会被识别并打开到网页上 如果想下载这个图片的话 就需要连接到后台读取文件并生成一个头信息下载.不过可以先给a标签加上一个download属性即可直接下载了. <a ...

  6. scrapy操作mysql/批量下载图片

    1.操作mysql items.py meiju.py 3.piplines.py 4.settings.py -------------------------------------------- ...

  7. 十四 web爬虫讲解2—Scrapy框架爬虫—豆瓣登录与利用打码接口实现自动识别验证码

    打码接口文件 # -*- coding: cp936 -*- import sys import os from ctypes import * # 下载接口放目录 http://www.yundam ...

  8. Python爬虫从入门到放弃(十四)之 Scrapy框架中选择器的用法

    Scrapy提取数据有自己的一套机制,被称作选择器(selectors),通过特定的Xpath或者CSS表达式来选择HTML文件的某个部分Xpath是专门在XML文件中选择节点的语言,也可以用在HTM ...

  9. 爬虫3 requests基础之下载图片用content(二进制内容)

    res = requests.get('http://soso3.gtimg.cn/sosopic/0/11129365531347748413/640') # print(res.content) ...

随机推荐

  1. MySQL日期时间字段

    mysql支持的日期时间类型有:DATETIME. TIMESTAMP.DATE.TIME.YEAR. 几种类型比较如下: DATETIME DATETIME 用于表示 年月日 时分秒,是 DATE和 ...

  2. [luogu4234]最小差值生成树

    [luogu4234]最小差值生成树 luogu 从小到大枚举边,并连接,如果已连通就删掉路径上最小边 lct维护 \(ans=min(E_{max}-E_{min})\) #include<b ...

  3. 报错:SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

    Outline SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: trunc ...

  4. Android系统移植与调试之------->如何添加一个adb wifi无线调试的功能【开发者选项】-【Wifi调试】

    首先弄懂怎么设置adb wifi无线调试的功能,如下所示. 1. 手机端开启adb tcp连接端口 :/$setprop service.adb.tcp.port :/$stop adbd :/$st ...

  5. Android “swipe” vs “fling”

    onFling will get executed when a user makes a "fling" motion, and said motion has a veloci ...

  6. AngularJs使用过程中,在ng-repeat中使用track by

    1.问题描述: 点击删除后:table中的被选中设备确实被删除了,但是data-table并没有重新加载出来, 查看js代码: 先对$scope.data_table进行了destroy(),然后重新 ...

  7. 基于docker 搭建Elasticsearch5.6.4 分布式集群

    说明: 准备2台机器,我这里有192. 和 192.168.0.164 192.168.0.164 作为master 192.168.0.107 作为普通node 一.环境 .docker 环境 .E ...

  8. 003-Java非堆CodeCache详解

    一.概述 Java的内存由堆和非堆两个部分组成.对于堆来说,它的组成是比较确定的,它包含了年轻代和年老代两个部分,而年轻代又是由Eden区和两个Survivor区组成.可是,非堆由哪些部分组成呢? 在 ...

  9. ionic学习笔记—创建项目

    环境搭建: 安装node.js  --> npm或cnpm   -->  安装jdk  -->  安装AndroidSDK  -->  安装cordova  -->  安 ...

  10. JS连等赋值的坑

    cnblogs标题: JS连等赋值的坑 关于JS连等赋值有个经典的笔试题: var a = {n: 1}; var b = a; a.x = a = {n: 2}; console.log(a.x); ...