当前位置: 首页 > news >正文

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++>【继承篇】

​ ✨前言✨ 🎓作者:【 教主 】 📜文章推荐: ☕博主水平有限,如有错误,恳请斧正。 📌机会总是留给有准备的人,越努力,越幸运! 💦导航助手&#x1…...

size_t 和double相乘怎么转换size_t

在C中,size_t和double可以直接相乘,结果会自动转换为double类型。如果你想要得到的结果是size_t类型,你需要进行显式类型转换。但是要注意,double转size_t可能会丢失小数部分,只保留整数部分。 以下是一个例子&#x…...

C# 的一些好用的语法糖介绍

C# 中有很多语法糖&#xff08;Syntactic sugar&#xff09;&#xff0c;它们是一些语言特性&#xff0c;使得编写代码更加简洁、易读、更具表现力。 Lambda 表达式&#xff1a; Lambda 表达式允许你编写简洁的匿名函数。例如&#xff1a; Func<int, int, int> add (a…...

wordpress后台更新后 前端没变化的解决方法

使用siteground主机的wordpress网站&#xff0c;会出现更新了网站内容和修改了php模板文件、js文件、css文件、图片文件后&#xff0c;网站没有变化的情况。 不熟悉siteground主机的新手&#xff0c;遇到这个问题&#xff0c;就很抓狂&#xff0c;明明是哪都没操作错误&#x…...

Auto-Coder使用GPT-4o完成:在用TabPFN这个模型构建一个预测未来3天涨跌的分类任务

通过akshare库&#xff0c;获取股票数据&#xff0c;并生成TabPFN这个模型 可以识别、处理的格式&#xff0c;写一个完整的预处理示例&#xff0c;并构建一个预测未来 3 天股价涨跌的分类任务 用TabPFN这个模型构建一个预测未来 3 天股价涨跌的分类任务&#xff0c;进行预测并输…...

《用户共鸣指数(E)驱动品牌大模型种草:如何抢占大模型搜索结果情感高地》

在注意力分散、内容高度同质化的时代&#xff0c;情感连接已成为品牌破圈的关键通道。我们在服务大量品牌客户的过程中发现&#xff0c;消费者对内容的“有感”程度&#xff0c;正日益成为影响品牌传播效率与转化率的核心变量。在生成式AI驱动的内容生成与推荐环境中&#xff0…...

学校招生小程序源码介绍

基于ThinkPHPFastAdminUniApp开发的学校招生小程序源码&#xff0c;专为学校招生场景量身打造&#xff0c;功能实用且操作便捷。 从技术架构来看&#xff0c;ThinkPHP提供稳定可靠的后台服务&#xff0c;FastAdmin加速开发流程&#xff0c;UniApp则保障小程序在多端有良好的兼…...

LLM基础1_语言模型如何处理文本

基于GitHub项目&#xff1a;https://github.com/datawhalechina/llms-from-scratch-cn 工具介绍 tiktoken&#xff1a;OpenAI开发的专业"分词器" torch&#xff1a;Facebook开发的强力计算引擎&#xff0c;相当于超级计算器 理解词嵌入&#xff1a;给词语画"…...

Axios请求超时重发机制

Axios 超时重新请求实现方案 在 Axios 中实现超时重新请求可以通过以下几种方式&#xff1a; 1. 使用拦截器实现自动重试 import axios from axios;// 创建axios实例 const instance axios.create();// 设置超时时间 instance.defaults.timeout 5000;// 最大重试次数 cons…...

HTML前端开发:JavaScript 常用事件详解

作为前端开发的核心&#xff0c;JavaScript 事件是用户与网页交互的基础。以下是常见事件的详细说明和用法示例&#xff1a; 1. onclick - 点击事件 当元素被单击时触发&#xff08;左键点击&#xff09; button.onclick function() {alert("按钮被点击了&#xff01;&…...

Spring Cloud Gateway 中自定义验证码接口返回 404 的排查与解决

Spring Cloud Gateway 中自定义验证码接口返回 404 的排查与解决 问题背景 在一个基于 Spring Cloud Gateway WebFlux 构建的微服务项目中&#xff0c;新增了一个本地验证码接口 /code&#xff0c;使用函数式路由&#xff08;RouterFunction&#xff09;和 Hutool 的 Circle…...

力扣-35.搜索插入位置

题目描述 给定一个排序数组和一个目标值&#xff0c;在数组中找到目标值&#xff0c;并返回其索引。如果目标值不存在于数组中&#xff0c;返回它将会被按顺序插入的位置。 请必须使用时间复杂度为 O(log n) 的算法。 class Solution {public int searchInsert(int[] nums, …...

网站指纹识别

网站指纹识别 网站的最基本组成&#xff1a;服务器&#xff08;操作系统&#xff09;、中间件&#xff08;web容器&#xff09;、脚本语言、数据厍 为什么要了解这些&#xff1f;举个例子&#xff1a;发现了一个文件读取漏洞&#xff0c;我们需要读/etc/passwd&#xff0c;如…...