scrapy-1

news2024/10/6 17:16:18

1.scrapy

Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架。 可以应用在包括数据挖掘,信息处理 或存储历史数据等一系列的程序中。

2.scrapy项目的创建以及运行

1.创建scrapy项目:终端输入 scrapy startproject 项目名称
2.项目组成:

  • spiders
    • init.py 自定义的爬虫文件.py ‐‐‐》由我们自己创建,是实现爬虫核心功能的文件
    • init.py items.py ‐‐‐》定义数据结构的地方,是一个继承自scrapy.Item的类
  • middlewares.py ‐‐‐》中间件 代理
  • pipelines.py ‐‐‐》管道文件,里面只有一个类,用于处理下载数据的后续处理 默认是300优先级,值越小优先级越高(1‐1000)
  • settings.py ‐‐‐》配置文件 比如:是否遵守robots协议,User‐Agent定义等

3.创建爬虫文件:

创建爬虫文件:
(1)跳转到spiders文件夹 cd 目录名字/目录名字/spiders
(2)scrapy genspider 爬虫名字 网页的域名
爬虫文件的基本组成:

  • 继承scrapy.Spider类
    • name = ‘baidu’ ‐‐‐》 运行爬虫文件时使用的名字
    • allowed_domains ‐‐‐》 爬虫允许的域名,在爬取的时候,如果不是此域名之下的 url,会被过滤掉
    • start_urls ‐‐‐》 声明了爬虫的起始地址,可以写多个url,一般是一个
    • response.text ‐‐‐》响应的是字符串
    • response.body ‐‐‐》响应的是二进制文件
    • response.xpath()‐》xpath方法的返回值类型是selector列表
    • extract() ‐‐‐》提取的是selector对象的是data
    • extract_first() ‐‐‐》提取的是selector列表中的第一个数据
    • parse(self, response) ‐‐‐》解析数据的回调函数

运行爬虫文件:
scrapy crawl 爬虫名称 注意:应在spiders文件夹内执行

4.简单样例

4.1文件结构

请添加图片描述

4.2代码

import scrapy
class BaiduSpider(scrapy.Spider):
    # 爬虫的名字  用于运行爬虫的时候 使用的值
    name = 'baidu'
    # 允许访问的域名
    allowed_domains = ['http://www.baidu.com']
    # 起始的url地址  指的是第一次要访问的域名
    # start_urls 是在allowed_domains的前面添加一个http://
    #             在 allowed_domains的后面添加一个/
    start_urls = ['http://www.baidu.com/']

    # 是执行了start_urls之后 执行的方法   方法中的response 就是返回的那个对象
    # 相当于 response = urllib.request.urlopen()
    #       response  = requests.get()
    def parse(self, response):
        print('苍茫的天涯是我的爱')

5.简单样例

5.1文件结构

请添加图片描述

import scrapy


class CarSpider(scrapy.Spider):
    name = 'car'
    allowed_domains = ['https://car.autohome.com.cn/price/brand-15.html']
    start_urls = ['https://car.autohome.com.cn/price/brand-15.html']#ruguo 结尾是html的话,那么是不需要加上\

    def parse(self, response):
        #//div[@class='main-title']/a/text()
        #//div[@class="main-lever"]//span/span/text()
        name_list = response.xpath('//div[@class="main-title"]/a/text()')
        price_list = response.xpath('//div[@class="main-lever"]//span/span/text()')
        print(name_list)#输出的是一个列表
        '''
        [<Selector xpath='//div[@class="main-title"]/a/text()' data='宝马1系'>, <Selector xpath='//div[@class="main-title"]/a/text()' data='宝马3系'>, <Selector xp/div[@class="main-title"]/a/text()' data='宝马i3'>, <Selector xpath='//div[@class="main-title"]/a/text()' data='宝马5系'>, <Selector xpath='//div[@class="mitle"]/a/text()' data='宝马5系新能源'>, <Selector xpath='//div[@class="main-title"]/a/text()' data='宝马X1'>, <Selector xpath='//div[@class="main-title"]/a data='宝马X2'>, <Selector xpath='//div[@class="main-title"]/a/text()' data='宝马iX3'>, <Selector xpath='//div[@class="main-title"]/a/text()' data='宝马X3'lector xpath='//div[@class="main-title"]/a/text()' data='宝马X5'>, <Selector xpath='//div[@class="main-title"]/a/text()' data='宝马2系'>, <Selector xpath='[@class="main-title"]/a/text()' data='宝马4系'>, <Selector xpath='//div[@class="main-title"]/a/text()' data='宝马i4'>, <Selector xpath='//div[@class="main-"]/a/text()' data='宝马5系(进口)'>, <Selector xpath='//div[@class="main-title"]/a/text()' data='宝马6系GT'>]
        输出的是列表中的每一个data中的值
        宝马1系
宝马3系
宝马i3
宝马5系
宝马5系新能源
宝马X1
宝马X2
宝马iX3
宝马X3
宝马X5
宝马2系
宝马4系
宝马i4
宝马5系(进口)

        '''
        for name in name_list:
            print(name.extract())
        print('============')
        print(price_list.extract_first())#获取得到的是第一个Selector的值的data。
        pass

6.完整样例

6.1 代码结构

请添加图片描述

请添加图片描述

6.2 代码

dang.py

import scrapy
from sccrapy_dangdang_095.items import SccrapyDangdang095Item

class DangSpider(scrapy.Spider):
    name = 'dang'
    # allowed_domains = ['http://e.dangdang.com/list-AQQG-dd_sale-0-1.html']
    # start_urls = ['http://e.dangdang.com/list-AQQG-dd_sale-0-1.html']#ruguo 结尾是html的话,那么是不需要加上\

    allowed_domains = ['category.dangdang.com']
    start_urls = ['http://category.dangdang.com/cp01.01.02.00.00.00.html']

    base_url = "http://category.dangdang.com/pg"
    page = 1

    def parse(self, response):
        #//div[@class="title"]/text()
        #//div[@class="price"]/span/text()

        #pipelines 下载数据
        #items 定义数据结构
        #所有的seletor的对象 都可以再次调用xpath方法
        li_list = response.xpath('//ul[@id="component_59"]/li')

        for li in li_list:
            #里面就有一个东西
            src = li.xpath('.//img/@data-original').extract_first()
            #第一张
            if src:
                src = src
            else:
                src = li.xpath('.//img/@src').extract_first()

            name = li.xpath('.//img/@alt').extract_first()#获取到名字
            price = li.xpath('.//p[@class="price"]/span[1]/text()').extract_first()#获取到p标签中的价格

            book = SccrapyDangdang095Item(src=src, name=name, price=price)

            #huoqu获取一个book就将book交给pipelines
            yield book

        if self.page < 100:
            self.page = self.page + 1

            url = self.base_url + str(self.page) + '-cp01.01.02.00.00.00.html'

            #             怎么去调用parse方法
            #             scrapy.Request就是scrpay的get请求
            #             url就是请求地址
            #             callback是你要执行的那个函数  注意不需要加()
            yield scrapy.Request(url=url, callback=self.parse)

        print('============')


items.py

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class SccrapyDangdang095Item(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    # tongshu通俗的说就是需要下载的数据都有什么

    #图片
    src = scrapy.Field()
    #名字
    name = scrapy.Field()
    #价格
    price = scrapy.Field()
    pass

pipelines.py

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter

# 如果想使用管道的话 那么就必须在settings中开启管道
class SccrapyDangdang095Pipeline:

    # 在爬虫文件开始的之前就执行的一个方法
    def open_spider(self,spider):
        self.fp = open('book.json','w',encoding='utf-8')

    # item就是yield后面的book对象
    def process_item(self, item, spider):
        self.fp.write(str(item))
        return item

    #在爬虫文件执行完之后 执行的方法
    def close_spider(self,spider):
        self.fp.close()



import urllib.request
# 多条管道开启
#    (1) 定义管道类
#   (2) 在settings中开启管道
# 'scrapy_dangdang_095.pipelines.DangDangDownloadPipeline':301
class DangDangDownloadPipeline:
    def process_item(self,item,spider):

        url = 'http:' + item.get('src')
        filename = './books/' + item.get('name') + '.jpg'
        urllib.request.urlretrieve(url=url, filename=filename)

        return item

setting.py

# Scrapy settings for sccrapy_dangdang_095 project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'sccrapy_dangdang_095'

SPIDER_MODULES = ['sccrapy_dangdang_095.spiders']
NEWSPIDER_MODULE = 'sccrapy_dangdang_095.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'sccrapy_dangdang_095 (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'sccrapy_dangdang_095.middlewares.SccrapyDangdang095SpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'sccrapy_dangdang_095.middlewares.SccrapyDangdang095DownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
#  管道可以有很多个  那么管道是有优先级的  优先级的范围是1到1000   值越小优先级越高
   'sccrapy_dangdang_095.pipelines.SccrapyDangdang095Pipeline': 300,


#    DangDangDownloadPipeline
   'sccrapy_dangdang_095.pipelines.DangDangDownloadPipeline':301
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

下载成功
请添加图片描述

请添加图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/194607.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

OpenMMLab 计算机视觉 # day1: 计算机视觉基础与OpenMMLab开源算法体系

相关资源: github 第一课 计算机视觉与 OpenMMLab 开源算法体系 张子豪 计算机视觉基础 计算机视觉&#xff1a;让计算机理解图像、视频。 计算机视觉的三大基础任务&#xff1a;图像分类(图像识别)、目标检测、图像分割任务。 根据目标数量&#xff0c;计算机视觉任务也分…

Bahdanau 注意力

在预测词元时&#xff0c;如果不是所有输入词元都是相关的&#xff0c;那么具有Bahdanau注意力的循环神经网络编码器-解码器会有选择地统计输入序列的不同部分。这是通过将上下文变量视为加性注意力池化的输出来实现的。 在循环神经网络编码器-解码器中&#xff0c;Bahdanau注…

Centos8中安装配置DVWA靶场环境详细流程

一、准备内容本文在Centos8中安装配置DVWA靶场&#xff0c;该靶场启动需具备【LinuxApacheMysqlPhp】四大环境&#xff1a;所以在后续的安装配置DVWA靶场时遇到问题首先需要排查Apache、Mysql、Php这三大环境是否正常启动&#xff08;若不能正常启动则需逐一排查解决&#xff0…

漏洞深度分析|CVE-2023-24162 hutool XML反序列化漏洞

项目介绍 Hutool是一个小而全的Java工具类库&#xff0c;通过静态方法封装&#xff0c;降低相关API的学习成本&#xff0c;提高工作效率&#xff0c;使Java拥有函数式语言般的优雅&#xff0c;让Java语言也可以“甜甜的”。 Hutool中的工具方法来自每个用户的精雕细琢&#x…

ARP攻击

一、ARP1.1、ARP介绍地址解析协议&#xff0c;即ARP&#xff08;Address Resolution Protocol&#xff09;&#xff0c;是根据IP地址获取物理地址&#xff08;MAC地址&#xff09;的一个TCP/IP协议.每台主机都设有一个ARP高速缓存&#xff0c;里面有本局域网上的主机和路由器的…

优思学院|六西格玛团队缺乏方向感怎么办?原因是...

团队方向感是一个六西格玛项目成功的关键因素。它确保团队成员有共同的目标&#xff0c;清晰的任务分配&#xff0c;以及明确的行动计划。有了方向感&#xff0c;团队成员可以有效地利用自己的才能和知识&#xff0c;共同努力实现团队的目标。团队方向感不仅有助于提高团队的效…

4种通过iframe跨域与其他页面通信的方式

目录 4种通过iframe跨域与其他页面通信的方式 location.hash window.name postMessage document.domain降域 4种通过iframe跨域与其他页面通信的方式 location.hash 在url中&#xff0c;http://www.baidu.com#helloword的#helloworad就是location.hash&#xff0c;改变has…

SpringMVC之bean加载控制

目录 一&#xff1a;问题分析 二&#xff1a;思路分析 三&#xff1a;环境准备 四&#xff1a;设置bean加载控制 知识点1&#xff1a;ComponentScan 一&#xff1a;问题分析 入门案例的内容已经做完了&#xff0c;在入门案例中我们创建过一个SpringMvcConfig的配置类&#x…

Redis如何实现分布式锁?

&#x1f4e2;&#x1f4e2;&#x1f4e2;&#x1f4e3;&#x1f4e3;&#x1f4e3; 哈喽&#xff01;大家好&#xff0c;我是【一心同学】&#xff0c;一位上进心十足的【Java领域博主】&#xff01;&#x1f61c;&#x1f61c;&#x1f61c; ✨【一心同学】的写作风格&#x…

OpenMMLab学习笔记(一)

OpenMMLab学习笔记&#xff08;一&#xff09; day01 计算机视觉与OpenMMLab开源算法体系 1. 基本知识 计算机视觉的基础任务&#xff1a;分类、分类和定位、物体检测、分割&#xff08;语义分割、实例分割&#xff09;&#xff0c;其中实例分割统一种类索引不同 注意语义分…

indexedDB存储

一、概述 随着浏览器的功能不断增强&#xff0c;越来越多的网站开始考虑&#xff0c;将大量数据储存在客户端&#xff0c;这样可以减少从服务器获取数据&#xff0c;直接从本地获取数据。 现有的浏览器数据储存方案&#xff0c;都不适合储存大量数据&#xff1a;Cookie 的大小…

rocketmq 笔记

cap理论 Consistency&#xff08;一致性&#xff09;Availability&#xff08;可用性&#xff09;Partition tolerance&#xff08;分区容忍性&#xff09; ①一致性&#xff1a;对于客户端的每次读操作&#xff0c;要么读到的是最新的数据&#xff0c;要么读取失败。换句话说…

ElasticSearch -- Prometheus+Grafana监控

向导介绍部署Prometheus配置Grafana下载仪表盘导入仪表盘报警核心指标集群健康和节点可用性主机级别的系统和网络指标JVM内存和垃圾回收搜索和索引性能资源饱和度注册自动重启介绍 Prometheus官方提供了ES的exporter&#xff1a;EsExporter Github地址&#xff1a;elasticsea…

【Vue】Vue不同版本的基本使用

一、Vue的版本 1. Vue1.x几乎被淘汰&#xff0c;不再建议学习与使用。2. Vue2.x<scriptsrc"" target"_blank">https://cdn.jsdelivr.net/npm/vue2.6.14"></script>3. Vue3.x<scriptsrc"" target"_blank">ht…

【IO异常】HTTP请求报错Error writing to server

报错信息如下&#xff1a; [2023-01-04 13:36:02.185]-ERROR-[biz:aplus-task-oms1060189862335877121][sys:aplus-cms-tran1060189866052390912][com.phfund.aplus.cms.tran.module.counter.service.impl.OcrServiceImpl-102][调用远程服务发送文件异常:] cn.hutool.http.Http…

一、HTML5

文章目录一、HTML5二、html5的基本结构三、基本标签四、HTML常用标记4.1 文本标题(h1-h6)4.2 段落文本p4.4 空格4.5 换行 br4.6 水平线4.7 加粗标记4.8 倾斜4.9 扩展4.10 列表4.10.1 ul 无序列表4.10.2 ol 有序列表4.10.3 dl 自定义列表五、块级标签、行级标签一、HTML5 H5是H…

洛谷 P1886 滑动窗口 /【模板】单调队列

滑动窗口 /【模板】单调队列 题目描述 有一个长为 nnn 的序列 aaa&#xff0c;以及一个大小为 kkk 的窗口。现在这个从左边开始向右滑动&#xff0c;每次滑动一个单位&#xff0c;求出每次滑动后窗口中的最大值和最小值。 例如&#xff1a; The array is [1,3,−1,−3,5,3,…

辨别三星内存条的真假

目录前言一、三星内存为什么水深&#xff1f;二、通过物理手段辨别1.包装2.日期3.是否透光4.颜色5.电阻颜色6.颗粒丝印&#xff08;重点&#xff09;7.其他标签或字迹结语前言 本文截止2023.2.2&#xff0c;针对笔记本内存条 省流&#xff1a;直接JD自营 最近随手在tb买了条三星…

快速掌握任意 Android 应用的抓包

抓包是流量分析的基础&#xff0c;也是安全研究重要的一环。抓包软件有很多种&#xff0c;如 Burpsuite、mitmproxy 以及 Fiddle&#xff0c;抓包方式常见的有设置系统代理、AP 热点抓包、透明代理等。不同方式有不同优缺点&#xff0c;也有不同的应用场景。相信很多安全研究者…

Google Analytics | 学习笔记

一.简介 1.什么是GA&#xff1f; 是谷歌开发的一款分析网页流量的工具&#xff0c;可以帮助网站解决数据分析与统计的问题&#xff0c;并且将这些数据可视化展现报告出来&#xff0c;帮助网站商家更好的分析受众&#xff0c;流量等&#xff0c;从而更好地进行运营网站营销等 …