Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Scrapy 持续自动翻页爬取数据

Scrapy 持续自动翻页爬取数据

原创
作者头像
待你如初见
修改于 2021-04-27 07:09:16
修改于 2021-04-27 07:09:16
5.4K0
举报
文章被收录于专栏:待你如初见待你如初见

概述

  • 方案一:
  • 根据URL寻找规律适用于没有下一页button的网页,或者button不是url的网页
  • 方案二:
    • 根据下一页button获取button内容

修改代码

  • 这里使用方案二
  • 通过F12 得到下一页buton的Xpath
图片.png
图片.png
代码语言:txt
AI代码解释
复制
# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request
from urllib.parse import urljoin

class BookSpider(scrapy.Spider):
    name = 'book'
    allowed_domains = ['dangdang.com']
    start_urls = ['http://category.dangdang.com/cp01.54.92.01.00.00.html']
    page_url = None

    def parse(self, response):
        # 获取到所有有效li 获取最后一页时发现xpath发生改变 使用模糊匹配
        for each in response.xpath('//ul[contains(@id, "component_5")]/li'):
            # 标题
            title = each.xpath("p[1]/a/text()").extract()
            # 价格
            price = each.xpath("p[3]/span[1]/text()").extract()
            # 评论数
            star = each.xpath("p[4]/a/text()").extract()
            # 详情介绍
            detail = each.xpath("p[2]/text()").extract()
            if not detail:
                detail = ["本书暂无描述、、、、、、"]
            print('detail', detail)
            print("title", title)
            print('price', price)
            print('star', star)
        # 获取下一页url
        self.page_url = response.xpath(
            '//div[@class="paging"]//ul//li[10]//a/@href').extract()
        # 当快结束时下一页xpath发生改变
        if not self.page_url:
            self.page_url = response.xpath(
                '//div[@class="paging"]//ul//li[8]//a/@href').extract()
        # page_url 是一个数组
        for next_url in self.page_url:
            yield Request(urljoin("http://category.dangdang.com", next_url), callback=self.parse)
  • 翻页爬取结束

补充

  • setting.py 解释
代码语言:txt
AI代码解释
复制
# -\*- coding: utf-8 -\*-

# Scrapy settings for BookSpider project

# 

# For simplicity, this file contains only settings considered important or

# commonly used. You can find more settings consulting the documentation:

# 

# [https://doc.scrapy.org/en/latest/topics/settings.html](https://doc.scrapy.org/en/latest/topics/settings.html)

# [https://doc.scrapy.org/en/latest/topics/downloader-middleware.html](https://doc.scrapy.org/en/latest/topics/downloader-middleware.html)

# [https://doc.scrapy.org/en/latest/topics/spider-middleware.html](https://doc.scrapy.org/en/latest/topics/spider-middleware.html)

# 爬虫名字

BOT\_NAME = 'BookSpider'

# 爬虫模块路径

SPIDER\_MODULES = 'BookSpider.spiders'

NEWSPIDER\_MODULE = 'BookSpider.spiders'

# Crawl responsibly by identifying yourself (and your website) on the user-agent

# 客户端user-agent 请求头

#USER\_AGENT = 'BookSpider (+[http://www.yourdomain.com](http://www.yourdomain.com))'

# Obey robots.txt rules

# 禁止爬虫配置 robots.txt 是遵循 Robot协议 的一个文件,它保存在网站的服务器中,它的作用是,告诉搜索引擎爬虫,

# 本网站哪些目录下的网页 不希望 你进行爬取收录。在Scrapy启动后,会在第一时间访问网站的 robots.txt 文件,然后决定该网站的爬取范围

# 在某些情况下我们想要获取的内容恰恰是被 robots.txt 所禁止访问的。所以,某些时候,我们就要将此配置项设置为 False ,拒绝遵守 Robot协议

ROBOTSTXT\_OBEY = False

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

# 并发请求数

# 当有CONCURRENT\_REQUESTS,没有DOWNLOAD\_DELAY 时,服务器会在同一时间收到大量的请求

# 当有CONCURRENT\_REQUESTS,有DOWNLOAD\_DELAY 时,服务器不会在同一时间收到大量的请求

#CONCURRENT\_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)

# See [https://doc.scrapy.org/en/latest/topics/settings.html#download-delay](https://doc.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

# 单IP访问并发数,如果有值则忽略:CONCURRENT\_REQUESTS\_PER\_DOMAIN,并且延迟下次秒数也应用在每个IP

#CONCURRENT\_REQUESTS\_PER\_IP = 16

# Disable cookies (enabled by default)

# 是否支持cookie,cookiejar进行操作cookie

#COOKIES\_ENABLED = False

# Disable Telnet Console (enabled by default)

# Telnet用于查看当前爬虫的信息,操作爬虫等...

# 使用telnet ip port ,然后通过命令操作

# TELNETCONSOLE\_ENABLED = True

# TELNETCONSOLE\_HOST = '127.0.0.1'

# TELNETCONSOLE\_PORT = 6023,

# 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://doc.scrapy.org/en/latest/topics/spider-middleware.html](https://doc.scrapy.org/en/latest/topics/spider-middleware.html)

#SPIDER\_MIDDLEWARES = {

# 'BookSpider.middlewares.BookspiderSpiderMiddleware': 543,

#}

# Enable or disable downloader middlewares

# See [https://doc.scrapy.org/en/latest/topics/downloader-middleware.html](https://doc.scrapy.org/en/latest/topics/downloader-middleware.html)

#DOWNLOADER\_MIDDLEWARES = {

# 'BookSpider.middlewares.BookspiderDownloaderMiddleware': 543,

#}

# Enable or disable extensions

# See [https://doc.scrapy.org/en/latest/topics/extensions.html](https://doc.scrapy.org/en/latest/topics/extensions.html)

#EXTENSIONS = {

# 'scrapy.extensions.telnet.TelnetConsole': None,

#}

# Configure item pipelines

# See [https://doc.scrapy.org/en/latest/topics/item-pipeline.html](https://doc.scrapy.org/en/latest/topics/item-pipeline.html)

# 定义pipeline处理请求

#ITEM\_PIPELINES = {

# 'BookSpider.pipelines.BookspiderPipeline': 300,

#}

# Enable and configure the AutoThrottle extension (disabled by default)

# See [https://doc.scrapy.org/en/latest/topics/autothrottle.html](https://doc.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://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings](https://doc.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'

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
安装和使用Scrapy
可以先创建虚拟环境并在虚拟环境下使用pip安装scrapy。 $ 项目的目录结构如下图所示。 (venv) $ tree . |____ scrapy.cfg |____ douban | |____ spiders | | |____ __init__.py | | |____ __pycache__ | |____ __init__.py | |____ __pycache__ | |____ middlewares.py | |____ settings.py | |____ items.py |
用户8442333
2021/05/21
4970
18.scrapy_maitian
ershoufang.py # -*- coding: utf-8 -*- import scrapy class ErshoufangSpider(scrapy.Spider): name = 'ershoufang' allowed_domains = ['maitian.com'] start_urls = ['http://maitian.com/'] def parse(self, response): pass zufang_spider.py
hankleo
2020/09/17
2880
Python爬虫Scrapy入门
Scrapy是Python开发的一个快速、高层次的屏幕抓取和web抓取框架,用于抓取web站点并从页面中提取结构化的数据。
里克贝斯
2021/05/21
6730
Python爬虫Scrapy入门
Scrapy框架: settings.py设置
# -*- coding: utf-8 -*- # Scrapy settings for maitian project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://doc.scrapy.org/en/latest/t
hankleo
2020/09/17
4470
17.splash_case06_ScrapySplashTest-master
taobao.py # -*- coding: utf-8 -*- from scrapy import Spider, Request from urllib.parse import quote from scrapysplashtest.items import ProductItem from scrapy_splash import SplashRequest script = """ function main(splash, args) splash.images_enabled = f
hankleo
2020/09/17
3960
python scrapy 爬虫实例_scrapy爬虫完整实例
本文主要通过实例介绍了scrapy框架的使用,分享了两个例子,爬豆瓣文本例程 douban 和图片例程 douban_imgs ,具体如下。
全栈程序员站长
2022/09/13
4620
利用Scrapy框架爬取LOL皮肤站高清壁纸
成品打包:点击进入 代码: 爬虫文件 # -*- coding: utf-8 -*- import scrapy from practice.items import PracticeItem from urllib import parse class LolskinSpider(scrapy.Spider): name = 'lolskin' allowed_domains = ['lolskin.cn'] start_urls = ['https://lolsk
SingYi
2022/07/14
4710
利用Scrapy框架爬取LOL皮肤站高清壁纸
python3 网络爬虫 实例1
pip install scrapy pip install pyOpenSSL pip install cryptography pip install CFFI pip install lxml pip install cssselect pip install Twisted
用户5760343
2019/12/13
9010
scrapy框架的介绍
Scrapy Engine(引擎): 负责Spider、ItemPipeline、Downloader、Scheduler中间的通讯,信号、数据传递等。
用户2337871
2019/07/19
6350
scrapy框架的介绍
python之crawlspider初探
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; font-family: "Courier New" !important; font-size: 12px !important;">""" 1、用命令创建一个crawlspider的模板:scrapy genspider -t crawl <爬虫名> <all_domain>,也可以手动创建 2、CrawlSpider中不能再有以parse为名字的数据提取方法,这个方法被CrawlSpider用来实现基础url提取等功能 3、一个Rule对象接受很多参数,首先第一个是包含url规则的LinkExtractor对象, 常有的还有callback(制定满足规则的解析函数的字符串)和follow(response中提取的链接是否需要跟进) 4、不指定callback函数的请求下,如果follow为True,满足rule的url还会继续被请求 5、如果多个Rule都满足某一个url,会从rules中选择第一个满足的进行操作 """</pre>
用户5760343
2019/08/02
5000
python之crawlspider初探
scrapy 爬取校花网,并作数据持久化处理
-:process_item方法中return item 的操作将item 传递给下一个即将被执行的管道类
百里丶落云
2023/11/14
4793
爬取4567电影网「建议收藏」
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/154556.html原文链接:https://javaforall.cn
全栈程序员站长
2022/09/06
2.3K0
【爬虫】python爬取MSDN站所有P2P下载链接
今日,msdn的新网站开放注册,然后体验了一波,发现要强制观看30S的广告才可以下载,因此就想提前把资源爬取下来以便后用。
SingYi
2022/07/13
7270
【爬虫】python爬取MSDN站所有P2P下载链接
scrapy-redis 分布式哔哩哔哩
scrapy里面,对每次请求的url都有一个指纹,这个指纹就是判断url是否被请求过的。默认是开启指纹即一个URL请求一次。如果我们使用分布式在多台机上面爬取数据,为了让爬虫的数据不重复,我们也需要一个指纹。但是scrapy默认的指纹是保持到本地的。所有我们可以使用redis来保持指纹,并且用redis里面的set集合来判断是否重复。
py3study
2020/01/16
4270
爬虫之scrapy-splash
目前,为了加速页面的加载速度,页面的很多部分都是用JS生成的,而对于用scrapy爬虫来说就是一个很大的问题,因为scrapy没有JS engine,所以爬取的都是静态页面,对于JS生成的动态页面都无法获得
周小董
2019/03/25
2K0
爬虫之scrapy-splash
Scrapy项目实战:爬取某社区用户详情
get_cookies.py from selenium import webdriver from pymongo import MongoClient from scrapy.crawler import overridden_settings # from segmentfault import settings import time import settings class GetCookies(object): def __init__(self): # 初始化组件
hankleo
2020/09/17
5720
《手把手带你学爬虫──初级篇》第6课 强大的爬虫框架Scrapy
Scrapy是一个Python爬虫应用框架,爬取和处理结构性数据非常方便。使用它,只需要定制开发几个模块,就可以轻松实现一个爬虫,让爬取数据信息的工作更加简单高效。
GitOPEN
2019/01/29
1.2K0
《手把手带你学爬虫──初级篇》第6课  强大的爬虫框架Scrapy
拥有了这个, 天下的美图都是你的!!!
今天本狗就给大家分享一串神奇的 ” 东东“, 它可以下载任意多的图片,因为本狗很喜欢那个网站的图片了, 所以就,,,, 而且都是高清图哦!!在此分享给大家!!!
Python知识大全
2020/02/13
5010
拥有了这个, 天下的美图都是你的!!!
Python网络爬虫(七)- 深度爬虫CrawlSpider1.深度爬虫CrawlSpider2.链接提取:LinkExtractor3.爬取规则:rules4.如何在pycharm中直接运行爬虫5.
目录: Python网络爬虫(一)- 入门基础 Python网络爬虫(二)- urllib爬虫案例 Python网络爬虫(三)- 爬虫进阶 Python网络爬虫(四)- XPath Python网络爬虫(五)- Requests和Beautiful Soup Python网络爬虫(六)- Scrapy框架 Python网络爬虫(七)- 深度爬虫CrawlSpider Python网络爬虫(八) - 利用有道词典实现一个简单翻译程序 深度爬虫之前推荐一个简单实用的库fake-useragent,可以伪装
Python攻城狮
2018/08/23
1.9K0
Python网络爬虫(七)- 深度爬虫CrawlSpider1.深度爬虫CrawlSpider2.链接提取:LinkExtractor3.爬取规则:rules4.如何在pycharm中直接运行爬虫5.
scapy 如何爬取妹子图全站
Scrapy是用纯Python实现一个为了爬取网站数据、提取结构性数据而编写的应用框架,用途非常广泛。
百里丶落云
2023/11/14
2420
推荐阅读
相关推荐
安装和使用Scrapy
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档