scrapy 爬虫:多线程爬取去微博热搜排行榜数据信息,进入详情页面拿取第一条微博信息,保存到本地text文件、保存到excel
如果想要保存到excel中可以看我的这个爬虫
使用Scrapy 框架开启多进程爬取贝壳网数据保存到excel文件中,包括分页数据、详情页数据,新手保护期快来看!!仅供学习参考,别乱搞_爬取贝壳成交数据c端用户登录-CSDN博客
最终数据展示 
QuotesSpider 爬虫程序
import scrapy
import refrom weibo_top.items import WeiboTopItemclass QuotesSpider(scrapy.Spider):name = "weibo_top"allowed_domains = ['s.weibo.com']def start_requests(self):yield scrapy.Request(url="https://s.weibo.com/top/summary?cate=realtimehot")def parse(self, response, **kwargs):trs = response.css('#pl_top_realtimehot > table > tbody > tr')count = 0for tr in trs:if count >= 30: # 获取前3条数据break # 停止处理后续数据item = WeiboTopItem()title = tr.css('.td-02 a::text').get()link = 'https://s.weibo.com/' + tr.css('.td-02 a::attr(href)').get()item['title'] = titleitem['link'] = linkif link:count += 1 # 增加计数器yield scrapy.Request(url=link, callback=self.parse_detail, meta={'item': item})else:yield itemdef parse_detail(self, response, **kwargs):item = response.meta['item']list_items = response.css('div.card-wrap[action-type="feed_list_item"]')limit = 0for li in list_items:if limit >= 1:break # 停止处理后续数据else:content = li.xpath('.//p[@class="txt"]/text()').getall()processed_content = [re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9【】,]', '', text) for text in content]processed_content = [text.strip() for text in processed_content if text.strip()]processed_content = ','.join(processed_content).replace('【,','【')item['desc'] = processed_contentprint(processed_content)yield itemlimit += 1 # 增加计数器
item 定义数据结构
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.htmlimport scrapyclass WeiboTopItem(scrapy.Item):title = scrapy.Field() # '名称'link = scrapy.Field() # '详情地址'desc = scrapy.Field() # 'desc'pass
中间件 设置cookie\User-Agent\Host
# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.htmlfrom scrapy import signals
from fake_useragent import UserAgent
# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapterclass WeiboTopSpiderMiddleware:# Not all methods need to be defined. If a method is not defined,# scrapy acts as if the spider middleware does not modify the# passed objects.@classmethoddef from_crawler(cls, crawler):# This method is used by Scrapy to create your spiders.s = cls()crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)return sdef process_spider_input(self, response, spider):# Called for each response that goes through the spider# middleware and into the spider.# Should return None or raise an exception.return Nonedef process_spider_output(self, response, result, spider):# Called with the results returned from the Spider, after# it has processed the response.# Must return an iterable of Request, or item objects.for i in result:yield idef process_spider_exception(self, response, exception, spider):# Called when a spider or process_spider_input() method# (from other spider middleware) raises an exception.# Should return either None or an iterable of Request or item objects.passdef process_start_requests(self, start_requests, spider):# Called with the start requests of the spider, and works# similarly to the process_spider_output() method, except# that it doesn’t have a response associated.# Must return only requests (not items).for r in start_requests:yield rdef spider_opened(self, spider):spider.logger.info("Spider opened: %s" % spider.name)class WeiboTopDownloaderMiddleware:# Not all methods need to be defined. If a method is not defined,# scrapy acts as if the downloader middleware does not modify the# passed objects.def __init__(self):self.cookie_string = "SUB=_2AkMS10-nf8NxqwFRmfoXyG3jaoxxygHEieKki758JRMxHRl-yT9vqhIrtRB6OVdhSYUGwRsrtuQyFPy_aLfaay7wguyu; SUBP=0033WrSXqPxfM72-Ws9jqgMF55529P9D9WhBJpfihr9Mo_TDhk.fIHFo; _s_tentry=www.baidu.com; UOR=www.baidu.com,s.weibo.com,www.baidu.com; Apache=5259811159487.941.1709629772294; SINAGLOBAL=5259811159487.941.1709629772294; ULV=1709629772313:1:1:1:5259811159487.941.1709629772294:"# self.referer = "https://sh.ke.com/chengjiao/"@classmethoddef from_crawler(cls, crawler):# This method is used by Scrapy to create your spiders.s = cls()crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)return sdef process_request(self, request, spider):cookie_dict = self.get_cookie()request.cookies = cookie_dictrequest.headers['User-Agent'] = UserAgent().randomrequest.headers['Host'] = 's.weibo.com'# request.headers["referer"] = self.refererreturn Nonedef get_cookie(self):cookie_dict = {}for kv in self.cookie_string.split(";"):k = kv.split('=')[0]v = kv.split('=')[1]cookie_dict[k] = vreturn cookie_dictdef process_response(self, request, response, spider):# Called with the response returned from the downloader.# Must either;# - return a Response object# - return a Request object# - or raise IgnoreRequestreturn responsedef process_exception(self, request, exception, spider):# Called when a download handler or a process_request()# (from other downloader middleware) raises an exception.# Must either:# - return None: continue processing this exception# - return a Response object: stops process_exception() chain# - return a Request object: stops process_exception() chainpassdef spider_opened(self, spider):spider.logger.info("Spider opened: %s" % spider.name)
管道 数据保存到记事本
# 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 ItemAdapterclass WeiboTopPipeline:def __init__(self):self.items = []def process_item(self, item, spider):# 将item添加到列表中self.items.append(item)print('\n\nitem',item)return itemdef close_spider(self, spider):# 打开文件,将所有items写入文件with open('weibo_top_data.txt', 'w', encoding='utf-8') as file:for item in self.items:title = item.get('title', '')desc = item.get('desc', '')output_string = f'{title}\n{desc}\n\n'file.write(output_string)
settings 配置多线程、延迟
# Scrapy settings for weibo_top 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.htmlBOT_NAME = "weibo_top"SPIDER_MODULES = ["weibo_top.spiders"]
NEWSPIDER_MODULE = "weibo_top.spiders"# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = "weibo_top (+http://www.yourdomain.com)"# Obey robots.txt rules
ROBOTSTXT_OBEY = False# Configure maximum concurrent requests performed by Scrapy (default: 16)
CONCURRENT_REQUESTS = 8# 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 = {
# "weibo_top.middlewares.WeiboTopSpiderMiddleware": 543,
#}# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {"weibo_top.middlewares.WeiboTopDownloaderMiddleware": 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 = {"weibo_top.pipelines.WeiboTopPipeline": 300,
}# 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 = 80
# The maximum download delay to be set in case of high latencies
AUTOTHROTTLE_MAX_DELAY = 160
# 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"# Set settings whose default value is deprecated to a future-proof value
REQUEST_FINGERPRINTER_IMPLEMENTATION = "2.7"
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
FEED_EXPORT_ENCODING = "utf-8"
相关文章:

scrapy 爬虫:多线程爬取去微博热搜排行榜数据信息,进入详情页面拿取第一条微博信息,保存到本地text文件、保存到excel
如果想要保存到excel中可以看我的这个爬虫 使用Scrapy 框架开启多进程爬取贝壳网数据保存到excel文件中,包括分页数据、详情页数据,新手保护期快来看!!仅供学习参考,别乱搞_爬取贝壳成交数据c端用户登录-CSDN博客 最终…...
网络、UDP编程
1.网络协议模型: OSI协议模型 应用层 实际发送的数据 表示层 发送的数据是否加密 会话层 是否建立会话连接 传输层 数据传输的方式(数据报、流式) 网络层 …...

VSCode安装与使用
1、下载地址:Documentation for Visual Studio Code 在 VS Code 中使用 Python - 知乎 (zhihu.com) 自动补全和智能感知检测、调试和单元测试在Python环境(包括虚拟环境和 conda 环境)之间轻松切换 在 VS Code 中安装插件非常的简单,只需要打开 VS Code…...
进程和线程的区别与联系
进程和线程是计算机系统中两个重要的概念,它们在操作系统中扮演着不同的角色,并有着不同的特点和用途。以下是详细信息: 进程。进程是操作系统中资源分配的基本单位,它包括程序、数据和进程控制块。每个进程都有自己的地址空间&a…...
6、Redis-KV设计、全局命令和安全性
目录 一、value设计 二、Key设计 三、全局命令——针对所有key 四、安全性 一、value设计 ①是否需要排序?需要:Zset ②需要缓存的数据是单个值还是多个值? 单个值:简单值---String;对象值---Hash多个值&#x…...

python之海龟绘图
海龟绘图(turtle)是一个Python内置的绘图库,也被称为“Turtle Graphics”或简称“Turtles”。它采用了一种有趣的绘图方式,模拟一只小海龟在屏幕上爬行,而小海龟爬行的路径就形成了绘制的图形。这种绘图方式最初源自20…...
Java实战:Spring Boot 实现异步记录复杂日志
日志记录是软件开发中非常重要的一环,它可以帮助我们快速定位问题、监控程序运行状态等。在 Spring Boot 应用中,异步记录日志是一种常见的需求。本文将详细介绍如何在 Spring Boot 中实现异步记录复杂日志,包括异步日志的基本原理、实现方式…...

“色狼”用英语怎么说?柯桥日常英语,成人英语口语学习
最近有粉丝问我"色狼"英文翻译是啥 首先声明不是"colour wolf"哈 关于“色狼”的英文表达有很多 快和C姐一起来看看吧! 1.pervert 这个单词的意思是变态、色狼 是对性变态者最直观的描述 He is such a pervert! I saw him lo…...

Docker前后端项目部署
目录 一、搭建项目部署的局域网 二、redis安装 三、MySQL安装 四、若依后端项目搭建 4.1 使用Dockerfile自定义镜像 五、若依前端项目搭建 一、介绍前后端项目 一张图带你看懂ruoyi的前后端项目部署 得出结论:需要4台服务器,都处于同一个局域网中…...
如何快速的搭建一个小程序
要快速搭建一个小程序,你可以按照以下步骤进行: 明确目标和需求:在开始搭建小程序之前,首先明确你的小程序的主要功能、目标用户以及希望实现的业务需求。这将帮助你更好地规划和设计小程序。选择小程序平台:根据你的…...
STM32自学☞AD多通道
涉及到的硬件有:光敏传感器,热敏传感器,红外对射传感器,电位器 通过adc将他们采集的模拟信号转换为数值 ad.c文件 #include "stm32f10x.h" #include "stm32f10x_adc.h" #include "ad.h" #inc…...

微服务之商城系统
一、商城系统建立之前的一些配置 1、nacos Nacos是一个功能丰富的开源平台,用于配置管理、服务发现和注册、健康检查等,帮助构建和管理分布式系统。 在linux上安装nacos容器的命令: docker run --name nacos-standalone -e MODEstandalone …...

安卓玩机工具推荐----高通芯片9008端口读写分区 备份分区 恢复分区 制作线刷包 工具操作解析
上期解析了下adb端口备份分区的有关操作 安卓玩机工具推荐----ADB状态读写分区 备份分区 恢复分区 查看分区号 工具操作解析 在以往的博文中对于高通芯片机型的分区读写已经分享了很多。相关类似博文 安卓备份分区----手动查询安卓系统分区信息 导出系统分区的一些基本操作 …...
全量知识系统问题及SmartChat给出的答复 之16 币圈生态链和行为模式
Q.42 币圈生态链和行为模式 我认为,上面和“币”有关的一系列概念和技术,按设计模式的划分 ,整体应该都属于行为模式,而且应该囊括行为模式的所有各个方面。 而行为又可以按照三种不同的导向(以目的或用途为导向、过…...

【MOMO_Tips】批量将word转换为PDF格式
批量将word转换为PDF格式 1.打开文件–>选项–>自定义功能区–>开发工具–>确定 2.点开开发工具,选择第一个visual basic 3.进入页面后找到插入–>模块,就可以看到这样的画面之后将下列vba代码复制粘贴到模块中 Sub ConvertWordsToPd…...

【JSON2WEB】08 Amis的事件和校验
【JSON2WEB】01 WEB管理信息系统架构设计 【JSON2WEB】02 JSON2WEB初步UI设计 【JSON2WEB】03 go的模板包html/template的使用 【JSON2WEB】04 amis低代码前端框架介绍 【JSON2WEB】05 前端开发三件套 HTML CSS JavaScript 速成 【JSON2WEB】06 JSON2WEB前端框架搭建 【J…...
抖店类目报白什么意思?什么类目需要报白?这次给你讲明白!
我是电商珠珠 不少新手在选择类目的时候,有些类目却无法选择,系统显示需要报白才可以。那什么是报白?怎么报白?今天我就一次性给你们讲清楚。 抖店类目报白什么意思? 根据官方的说法,报白就是针对一些比…...

<C++>【继承篇】
✨前言✨ 🎓作者:【 教主 】 📜文章推荐: ☕博主水平有限,如有错误,恳请斧正。 📌机会总是留给有准备的人,越努力,越幸运! 💦导航助手…...
size_t 和double相乘怎么转换size_t
在C中,size_t和double可以直接相乘,结果会自动转换为double类型。如果你想要得到的结果是size_t类型,你需要进行显式类型转换。但是要注意,double转size_t可能会丢失小数部分,只保留整数部分。 以下是一个例子&#x…...
C# 的一些好用的语法糖介绍
C# 中有很多语法糖(Syntactic sugar),它们是一些语言特性,使得编写代码更加简洁、易读、更具表现力。 Lambda 表达式: Lambda 表达式允许你编写简洁的匿名函数。例如: Func<int, int, int> add (a…...
变量 varablie 声明- Rust 变量 let mut 声明与 C/C++ 变量声明对比分析
一、变量声明设计:let 与 mut 的哲学解析 Rust 采用 let 声明变量并通过 mut 显式标记可变性,这种设计体现了语言的核心哲学。以下是深度解析: 1.1 设计理念剖析 安全优先原则:默认不可变强制开发者明确声明意图 let x 5; …...

eNSP-Cloud(实现本地电脑与eNSP内设备之间通信)
说明: 想象一下,你正在用eNSP搭建一个虚拟的网络世界,里面有虚拟的路由器、交换机、电脑(PC)等等。这些设备都在你的电脑里面“运行”,它们之间可以互相通信,就像一个封闭的小王国。 但是&#…...

安宝特方案丨XRSOP人员作业标准化管理平台:AR智慧点检验收套件
在选煤厂、化工厂、钢铁厂等过程生产型企业,其生产设备的运行效率和非计划停机对工业制造效益有较大影响。 随着企业自动化和智能化建设的推进,需提前预防假检、错检、漏检,推动智慧生产运维系统数据的流动和现场赋能应用。同时,…...

对WWDC 2025 Keynote 内容的预测
借助我们以往对苹果公司发展路径的深入研究经验,以及大语言模型的分析能力,我们系统梳理了多年来苹果 WWDC 主题演讲的规律。在 WWDC 2025 即将揭幕之际,我们让 ChatGPT 对今年的 Keynote 内容进行了一个初步预测,聊作存档。等到明…...

第 86 场周赛:矩阵中的幻方、钥匙和房间、将数组拆分成斐波那契序列、猜猜这个单词
Q1、[中等] 矩阵中的幻方 1、题目描述 3 x 3 的幻方是一个填充有 从 1 到 9 的不同数字的 3 x 3 矩阵,其中每行,每列以及两条对角线上的各数之和都相等。 给定一个由整数组成的row x col 的 grid,其中有多少个 3 3 的 “幻方” 子矩阵&am…...

【Oracle】分区表
个人主页:Guiat 归属专栏:Oracle 文章目录 1. 分区表基础概述1.1 分区表的概念与优势1.2 分区类型概览1.3 分区表的工作原理 2. 范围分区 (RANGE Partitioning)2.1 基础范围分区2.1.1 按日期范围分区2.1.2 按数值范围分区 2.2 间隔分区 (INTERVAL Partit…...
Java 二维码
Java 二维码 **技术:**谷歌 ZXing 实现 首先添加依赖 <!-- 二维码依赖 --><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.5.1</version></dependency><de…...

C++:多态机制详解
目录 一. 多态的概念 1.静态多态(编译时多态) 二.动态多态的定义及实现 1.多态的构成条件 2.虚函数 3.虚函数的重写/覆盖 4.虚函数重写的一些其他问题 1).协变 2).析构函数的重写 5.override 和 final关键字 1&#…...
Mysql8 忘记密码重置,以及问题解决
1.使用免密登录 找到配置MySQL文件,我的文件路径是/etc/mysql/my.cnf,有的人的是/etc/mysql/mysql.cnf 在里最后加入 skip-grant-tables重启MySQL服务 service mysql restartShutting down MySQL… SUCCESS! Starting MySQL… SUCCESS! 重启成功 2.登…...

Vue ③-生命周期 || 脚手架
生命周期 思考:什么时候可以发送初始化渲染请求?(越早越好) 什么时候可以开始操作dom?(至少dom得渲染出来) Vue生命周期: 一个Vue实例从 创建 到 销毁 的整个过程。 生命周期四个…...