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

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

转载自:https://www.jianshu.com/p/8f22cace85c7

标签选择器对象

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)                                       #返回标签对象

image

image

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

image

# -*- 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)  #返回类容列表

image

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

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保存路径

image

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)
相关文章
|
1月前
|
数据采集 存储 Python
python实现 Web 爬虫。
python实现 Web 爬虫。
31 1
|
3月前
|
数据采集 存储 数据处理
Scrapy:Python网络爬虫框架的利器
在当今信息时代,网络数据已成为企业和个人获取信息的重要途径。而Python网络爬虫框架Scrapy则成为了网络爬虫工程师的必备工具。本文将介绍Scrapy的概念与实践,以及其在数据采集和处理过程中的应用。
23 1
|
1月前
|
数据采集 数据可视化 数据挖掘
使用Python编写Web爬虫实现数据采集与分析
在当今信息化时代,数据是企业发展和决策的重要依据。本文将介绍如何使用Python编写Web爬虫来实现对特定网站数据的自动采集,并结合数据分析技术,为读者展示如何利用爬虫技术获取有价值的信息并进行有效的数据处理和分析。
|
4月前
|
数据采集 调度 Python
Scrapy爬虫中合理使用time.sleep和Request
Scrapy爬虫中合理使用time.sleep和Request
|
1天前
|
数据采集 存储 JSON
Python爬虫面试:requests、BeautifulSoup与Scrapy详解
【4月更文挑战第19天】本文聚焦于Python爬虫面试中的核心库——requests、BeautifulSoup和Scrapy。讲解了它们的常见问题、易错点及应对策略。对于requests,强调了异常处理、代理设置和请求重试;BeautifulSoup部分提到选择器使用、动态内容处理和解析效率优化;而Scrapy则关注项目架构、数据存储和分布式爬虫。通过实例代码,帮助读者深化理解并提升面试表现。
10 0
|
8天前
|
前端开发 搜索推荐 数据安全/隐私保护
HTML标签详解 HTML5+CSS3+移动web 前端开发入门笔记(四)
HTML标签详解 HTML5+CSS3+移动web 前端开发入门笔记(四)
18 1
|
1月前
|
数据采集 Web App开发 搜索推荐
项目配置之道:优化Scrapy参数提升爬虫效率
项目配置之道:优化Scrapy参数提升爬虫效率
|
1月前
|
前端开发 JavaScript 安全
深入探索 Qt6 web模块 WebEngineCore:从基础原理到高级应用与技巧
深入探索 Qt6 web模块 WebEngineCore:从基础原理到高级应用与技巧
72 0
|
3月前
|
数据采集 存储 调度
Scrapy:解锁网络爬虫新境界
在当今信息爆炸的时代,获取并处理大量网络数据是互联网行业中至关重要的一环。Python网络爬虫框架Scrapy作为一款高效、灵活的工具,为开发者提供了强大的能力来抓取、解析和存储各类网页信息。本文将介绍Scrapy的概念、主要特点以及实践经验,帮助读者掌握这一工具,并在实际项目中应用。
|
3月前
|
数据采集 存储 机器人
Scrapy网络爬虫框架——从入门到实践
网络爬虫已经成为了信息获取的必备工具之一,而Scrapy作为Python中最流行的网络爬虫框架之一,具有高效、可扩展、易用等特点。本文将深入介绍Scrapy框架的概念和实践,帮助读者快速掌握构建高质量网络爬虫的方法。
57 0