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"

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

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

相关文章

Bee Mobile组件库重磅升级

Bee Mobile组件库重磅升级! 丰富强大的组件移动预览快速上手create-bee-mobile Bee Mobile组件库重磅升级! Bee Mobile组件库最新 v1.0.0 版本,支持最新的 React v18。 主页:Bee Mobile 丰富强大的组件 一共拥有50多个组件&…

Java面向对象总结 ( 知识点 | 代码详解 )

类和对象 什么是类? ● 概念:具有相同特征(同一类)事物的抽象描述,如人类,车类,学生类等。 类的结构: ● 变量: 事物属性的描述(名词) ● 方法: 事物的行为(可以做…

基于Flask的宠物领养系统的设计与实现

基于Flask的宠物领养系统的设计与实现 涉及技术:python3.10flaskmysql8.0 系统分为普通用户和管理员两种角色,普通用户可以浏览搜索宠物,申请领养宠物;管理员可以分布宠物信息,管理系统等。 采用ORM模型创建数据&am…

QT----云服务器部署Mysql,Navicat连接1698 -Access denied for user ‘root‘@‘‘

阿里云有活动,白嫖了一年的新加坡轻量级服务器,有点卡,有时候要开梯子 白嫖300元优惠券 目录 1 安装启动Mysql服务2 更改连接权限2.1 Navicat连接报错1698 -Access denied for user root 3 qt连接云服务器数据库 1 安装启动Mysql服务 我使用…

f5——>字符串三角

暴力破解,双层循环,注意复制到新列表用append,这样更不容易出错 格式还是“”.join(str)

Grid网格布局的基本使用

文章目录 什么是网格布局属性display 属性grid-row-gap 属性, grid-column-gap 属性, grid-gap 属性grid-template-areas 属性grid-auto-flow 属性justify-items 属性 , align-items 属性, place-items 属性justify-content 属性 …

Java高频面试之集合篇

Java 中常用的容器有哪些? ArrayList 和 LinkedList 的区别? ArrayList 是基于数组实现的,LinkedList 是基于链表实现的. ArrayList实现了RandomAccess接口,可基于下标访问. LinkedList 实现了Deque /dek/,可以当做双端队列使用. 插入效率对比 如果从头部…

Unity的滑动控制相机跟随和第三人称视角三

Unity的相机跟随和第三人称视角三 第三人称相机优化介绍讲解拖动事件相机逻辑人物移动逻辑总结 第三人称相机优化 Unity第三人称相机视角一 Unity第三人称相机视角二 介绍 之前相机视角讲过了两篇文章了,但是都是自动旋转视角,今天来了新需求&#xf…

支部管理系统微信小程序(管理端+用户端)flask+vue+mysql+微信小程序

系统架构如图所示 高校D支部管理系统 由web端和微信小程序端组成,由web端负责管理,能够收缴费用、发布信息、发布问卷、发布通知等功能 部分功能页面如图所示 微信小程序端 包含所有源码和远程部署,可作为毕设课设

Java 数据结构之链表

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {if (headA null || headB null) return null;ListNode pA headA, pB headB;while (pA ! pB) {pA pA null ? headB : pA.next;pB pB null ? headA : pB.next;}return pA;} public ListNode rev…

数据库系列之:什么是 SAP HANA?

数据库系列之:什么是 SAP HANA? 一、什么是 SAP HANA?二、什么是内存数据库?三、SAP HANA 有多快?四、SAP HANA 的十大优势五、SAP HANA 架构六、数据库设计七、数据库管理八、应用开发九、高级分析十、数据虚拟化 一、…

1-安装rabbitmq

rabbitmq官网: https://www.rabbitmq.com/docs/download 本机环境:mac,使用orbstack提供的docker 使用docker部署rabbitmq docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3.13-management 然后报错&#xf…

信息安全服务规范包括哪些方面

信息安全服务规范是确保信息系统安全稳定运行的重要指导原则和操作准则。在信息化高速发展的今天,信息安全已经成为国家、企业乃至个人不可忽视的重要议题。因此,制定和执行信息安全服务规范对于保障信息安全、维护社会秩序具有重要意义。 信息安全服务规…

VScode+Zotero+Latex文献引用联动

一、VScodeLatex联动 1、VScode的安装 2、texlive.iso安装 可以参考以下,也可以忽略所有直接一步一步默认安装 https://zhuanlan.zhihu.com/p/442308176 3、Vscode的插件安装:【latex workshop】 4、打开设置,搜索json,然后点击…

MIT 6.S081---Lab: Multithreading

Uthread: switching between threads (moderate) 修改uthread.c,在thread中新增context字段: 修改uthread.c,在thread_create函数中新增以下逻辑: 修改uthread.c中的thread_switch函数定义: 修改uthread.c中的th…

你不得不知道的Python AI库

Python是人工智能(AI)和机器学习(ML)领域中使用最广泛的编程语言之一,拥有丰富的库支持各种AI和ML任务。本文介绍一些经典的Python AI库。 1. NumPy 简介:NumPy(Numerical Python)…

centos7中python3.10找不到openssl解决方案

如果有用其他方法安装了其他版本openssl,记得卸载其他的openssl,删除其他的openssl相关文件。 yum remove openssl* rm -rf ***下载最新版的openssl文件 按照官网安装方法安装openssl 官方安装地址https://docs.python.org/3/using/unix.html#on-linu…

代码随想录算法训练营第13天

239. 滑动窗口最大值 &#xff08;一刷至少需要理解思路&#xff09; 方法&#xff1a;暴力法 &#xff08;时间超出限制&#xff09; 注意&#xff1a; 代码&#xff1a; class Solution { public:vector<int> maxSlidingWindow(vector<int>& nums, int k…

数据分析方法(一)|认知数据

在进行数据分析时&#xff0c;很多人拿到数据之后没有头绪&#xff0c;在没有需求的情况下不知道从何做起&#xff0c;此时我们不妨先动起脑来理解数据。 分析数据之前&#xff0c;清晰的认识数据是非常重要的&#xff0c;通常我们可以从以下几个角度对数据进行深入了解&#x…

推荐5款极具效率的实用工具软件

​ 每次分享实用的软件,都会给人一种踏实和喜悦的感觉,这也是我热衷于搜集和推荐高效工具软件的原因。 1.个人日记软件——EDiary ​ EDiary是一款功能丰富的个人日记软件&#xff0c;用户可以在不联网的状态下使用&#xff0c;保护隐私。它支持日记、记事本、日历、事件提醒…