第十五天-爬虫项目实战

目录

1.介绍

2.代码

1.main.py

2.PageSider.py

3.DetailSpider.py

4.DataParse.py

5.Constant.py

6.HanderRequest.py


1.介绍

1. 使用多线程爬取网站

2.爬取数据后保存至excel

3.爬取网站(仅做测试)网创类项目爬取:https://www.maomp.com/

4..实现效果

2.代码

1.main.py

# coding:utf-8
import threadingimport requests
from  queue import Queue
from PageSpider import PageSpider
from DetailSpider import DetailSpider
from DataParse import DataParse
import xlsxwriter
import time
"""
爬取网站:https://www.maomp.com/wzjc/
爬取信息,保存至Excel
"""def start_page(threadsize,page_queue,detail_queue):# 开启线程,开始采集page页面page_spider_threadsize = threadsizepage_spider_list = []for i in range(1,page_spider_threadsize+1):pageSpiderThread = PageSpider(thread_name="页面采集线程"+str(i), page_queue=page_queue, detail_queue=detail_queue)# 启动线程pageSpiderThread.start()page_spider_list.append(pageSpiderThread)# 查看队列是否有数据while not page_queue:pass# 释放资源for page_spider in page_spider_list:if page_spider.is_alive():page_spider.join()def start_detail(threadsize,detail_queue,data_queue):# 开启线程,开始采集page页面detail_spider_threadsize = threadsizedetail_spider_list = []for i in range(1, detail_spider_threadsize + 1):detailSpiderThread = DetailSpider(thread_name="详情页采集线程" + str(i), detail_queue=detail_queue,data_queue=data_queue)# 启动线程detailSpiderThread.start()detail_spider_list.append(detailSpiderThread)# 查看队列是否有数据while not detail_queue:pass# 释放资源for detail_spider in detail_spider_list:if detail_spider.is_alive():detail_spider.join()def start_data_parse(threadsize,data_queue,book):# 开启线程,开始采集page页面lock=threading.Lock()sheet1 = book.add_worksheet("sheet1")title_data = ("网址", "标题", "发布时间", "内容")# 添加表头for index, title_datum in enumerate(title_data):sheet1.write(0, index, title_datum)spider_list = []for i in range(1, threadsize + 1):thread = DataParse(thread_name="数据解析线程" + str(i), data_queue=data_queue,lock=lock,sheet=sheet1)# 启动线程thread.start()spider_list.append(thread)# 查看队列是否有数据while not data_queue:pass# 释放资源for parse in spider_list:if parse.is_alive():parse.join()def main(xlswriter=None):#定义页面队列,存放page页信息page_queue = Queue()#定义详情页队列detail_queue = Queue()#定义详情页数据队列data_queue = Queue()page_start=1page_end=1for i in range(page_start,page_end+1):page_url="https://www.maomp.com/wzjc/page/{}/".format(i)page_queue.put(page_url)print("页面队列:",page_queue.qsize())#启动采集分页start_page(threadsize=3,page_queue=page_queue,detail_queue=detail_queue)#启动详情页采集start_detail(threadsize=3, detail_queue=detail_queue, data_queue=data_queue)# 启动数据解析#创建存放excel文件夹book = xlsxwriter.Workbook(time.strftime("%Y%m%d%H%M%S",time.gmtime())+"文件.xlsx")start_data_parse(threadsize=5,data_queue=data_queue,book=book)book.close()print("分页数据个数:",page_queue.qsize())print("详情页数据个数:", detail_queue.qsize())print("数据数据个数:", data_queue.qsize())if __name__ == '__main__':main()

2.PageSider.py

# coding:utf-8
import threading
from lxml import etree
import HanderRequestclass PageSpider(threading.Thread):"""页面url,请求多线程类"""def __init__(self,thread_name,page_queue,detail_queue):super(PageSpider,self).__init__()self.thread_name=thread_nameself.page_queue=page_queueself.detail_queue=detail_queuedef parse_detail_url(self,content):"""解析page页获取详情页url:param content:  page页text:return:  返回详情页url"""#页码返回数据html实例化item_html=etree.HTML(content)#解析出索引详情页URLdetail_urls=item_html.xpath("//h2[@class='entry-title']/a/@href")for url in detail_urls:#将详情页url存放到队列中self.detail_queue.put(url)def run(self):#实际发送请求print("{}启动".format(self.thread_name))#需要从page_queue队列中获取数据try:while not self.page_queue.empty():#从队列中获取数据,并设置为非阻塞状态page_url= self.page_queue.get(block=False)#请求页面链接response_text=HanderRequest.send_reqeust(page_url)if response_text:#解析详情urlself.parse_detail_url(response_text)except Exception as e:print("{} 执行异常:{}".format(self.thread_name,e))print("{}结束".format(self.thread_name))

3.DetailSpider.py

# coding:utf-8
import threading
from lxml import etree
import HanderRequestclass DetailSpider(threading.Thread):"""详情页url,请求详情页"""def __init__(self,thread_name,detail_queue,data_queue):super(DetailSpider,self).__init__()self.thread_name=thread_nameself.data_queue=data_queueself.detail_queue=detail_queuedef run(self):#实际发送请求print("{}启动".format(self.thread_name))#需要从page_queue队列中获取数据try:while not self.detail_queue.empty():#从队列中获取数据,并设置为非阻塞状态detail_url= self.detail_queue.get(block=False)#请求页面链接response_text=HanderRequest.send_reqeust(detail_url)if response_text:data={"url":detail_url,"html_content":response_text}#存放data_queuq数据self.data_queue.put(data)except Exception as e:print("{} 执行异常:{}".format(self.thread_name,e))print("{}结束".format(self.thread_name))

4.DataParse.py

# coding:utf-8
import threading
from lxml import etree
import Constantclass DataParse(threading.Thread):"""详情页数据处理"""def __init__(self,thread_name,data_queue,lock,sheet):super(DataParse,self).__init__()self.thread_name=thread_nameself.data_queue=data_queueself.lock=lockself.sheet=sheetdef __list_join(self,list):return "".join(list)def __parse(self,data):"""解析data_queue数据保存至excel中:return:"""html= etree.HTML(data.get("html_content"))data={"url":data.get("url"),"title": self.__list_join(html.xpath("//h1[@class='entry-title']/text()")),"put_date":self.__list_join(html.xpath("//span[@class='my-date']/text()")),"content_html":self.__list_join(html.xpath("//div[@class='single-content']//p/text()"))}#多线程,使用lock来进行控制并发with self.lock:#写入Excelfor index,e in enumerate(data):self.sheet.write(Constant.CURR_EXCEL_COL,index,data.get(e))Constant.CURR_EXCEL_COL += 1def run(self):#实际发送请求print("{}启动".format(self.thread_name))#需要从page_queue队列中获取数据try:while not self.data_queue.empty():#从队列中获取数据,并设置为非阻塞状态data_content= self.data_queue.get(block=False)#解析html数据self.__parse(data_content)except Exception as e:print("{} 执行异常:{}".format(self.thread_name,e))print("{}结束".format(self.thread_name))

5.Constant.py

# coding:utf-8# excel写入到第几列
CURR_EXCEL_COL=1

6.HanderRequest.py

注意修改cookie

# coding:utf-8import requestsdef send_reqeust(url):#发送数据headers={"Cookie":"xxx","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"}response=requests.get(url,headers=headers)if response.status_code==200 and response:return response.text

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

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

相关文章

Java已死?凛冽寒风,刺骨现实

文章首发于公众号:职谷智享 2024年,寒风凛冽,不仅吹进了人们的衣领,也吹进了程序员的心里。曾经风光无限的Java,如今似乎正在走向末路。 招聘需求骤减,求职者如过江之鲫 猎聘网的数据显示,20…

Linux 任务进程命令练习

1、通过ps命令的两种选项形式查看进程信息 2、通过top命令查看进程 3、通过pgrep命令查看sshd服务的进程号 4、查看系统进程树 5、使dd if/dev/zero of/root/file bs1M count8190 命令操作在前台运行 6、将第5题命令操作调入到后台并暂停 7、使dd if/dev/zero of/root/file2 bs…

Flutter中Future和Stream关系

Future和Stream类是Dart异步编程的核心。 Future 表示一个不会立即完成的计算过程。与普通函数直接返回结果不同的是异步函数返回一个将会包含结果的 Future。该 Future 会在结果准备好时通知调用者。 Stream 是一系列异步事件的序列。其类似于一个异步的 Iterable,…

力扣SQL50 大的国家 查询

Problem: 595. 大的国家 Code select name,population,area from World where area > 3000000 or population > 25000000;

国外站群服务器科普:定义、用途与价值

在数字化时代,服务器扮演着至关重要的角色,而站群服务器则是其中的一种特殊形态。尤其对于需要在全球范围内进行业务部署的企业或个人来说,国外站群服务器成为了不可或缺的工具。那么,国外站群服务器究竟是什么呢?它有哪些用途呢…

【Web安全靶场】sqli-labs-master 54-65 Challenges 与62关二分法和like模糊搜索

sqli-labs-master 54-65 Challenges 其他关卡和靶场见专栏… 文章目录 sqli-labs-master 54-65 Challenges第五十四关-联合注入第五十五关-联合注入第五十六关-联合注入第五十七关-联合注入第五十八关-报错注入第五十九关-报错注入第六十关-报错注入第六十一关-报错注入第六十…

抖音视频评论批量采集软件|视频数据提取工具

开发背景: 随着抖音视频的流行和使用频率增加,用户对批量采集抖音视频评论的需求逐渐凸显。传统的下载方式效率低下,无法满足快速采集数据的要求。为了解决这一问题,我们开发了一款基于C#的抖音视频评论批量采集软件,旨…

React富文本编辑器开发(三)

现在我们的编辑器显示的内容很单一,这自然不是我们的目标,让呈现的内容多元化是我们的追求。这就需要让编辑器能够接收多元素的定义。从初始数据的定义我们可以推断数据的格式远不止一种,那么其它类型的数据如何定义及呈现的呢,我…

kohya_ss, stable diffusion 显示MaxRetryError: HTTPSConnectionPool()的解决方法

说白了就是访问huggingface.co下载模型、json配置失败,需要挂梯子。 然而有时候明明开了梯子,网页端可以访问google、huggingface.co却依然报上述错。 这时候说明没有开代理,执行的脚本没有连接上梯子对应的端口。 解决办法:手…

【MySQL】数据库中常用的函数

目录 聚合函数COUNT()函数的多种用法COUNT(*)COUNT(主键)COUNT(1)COUNT(常量)COUNT(非主键)COUNT(distinct(字段)) COUNT()函数小结 字符函数length(str)函数:获取参数值的字节个数concat(str1,str2,...)函数:字符串拼接upper(str)、lower(str)函数:大小…

pdf.js使用步骤

使用pdfjs 网页在线预览需要后端服务器支持 1、下载PDF.js 源码包 地址:PDF.js 2、解压源码包,将源码包放置到后端服务器 3、后端部署完成后 访问 viewer.html 类似上图 4、访问在线pdf文件 http://localhost:8081/web/viewer.html?filexxxx.pdf …

[⑥5G NR]: 无线接口协议,信道映射学习

5G系统整体包括核心网、接入网以及终端部分,接入网与终端间通过无线空口协议栈进行连接。无线接口可分为三个协议层:物理层(L1)、数据链路层(L2)和网络层(L3)。 L1:物理…

JVM运行时数据区——虚拟机栈

文章目录 1、虚拟机栈概述1.1、StackOverflowError1.2、OOM异常 2、栈的存储单位3、局部变量表3.1、局部变量表简介3.2、Slot 4、操作数栈5、栈顶缓存技术6、动态链接7、方法的调用7.1、方法调用的分类7.2、虚方法与非虚方法7.3、关于invokedynamic指令7.4、方法重写的本质7.5、…

学习Fiddler抓包

Fiddler通过代理的方式获取程序http通讯的数据,可以用其检测网页和服务器的交互情况,能够记录所有客户端和服务器间的http请求,支持监视、设置端点、以及修改输入输出数据等功能 本质是一个web代理服务器,它的默认工作端口是8888.…

【24年最新版PythonPycharm安装】保姆级别安装教学!附激活码插件分享~

Python 下载安装 Python可以编译成可执行文件(。 py),并通过网络在计算机和其它终端设备上运行。它有内置的数据类型、函数、类和对象,可以将其用于各种目的,例如管理数据和脚本开发。 Python已经成为一种非常流行的…

面试数据库篇(mysql)- 04了解过索引吗?(什么是索引)

索引(index)是帮助MySQL高效获取数据的数据结构(有序)。在数据之外,数据库系统还维护着满足特定查找算法的数据结构(B+树),这些数据结构以某种方式引用(指向)数据, 这样就可以在这些数据结构上实现高级查找算法,这种数据结构就是索引。 B-Tree,B树是…

代码随想录-动态规划

爬楼梯 class Solution {public int climbStairs(int n) {int[] dp new int[n1];dp[0] 1;dp[1] 1;for(int i 2;i < n; i){dp[i] dp[i-1] dp[i-2];}return dp[n];} }746.使用最小花费爬楼梯 class Solution {public int minCostClimbingStairs(int[] cost) {int len …

Verilog语言支持

Verilog语言支持 介绍 本章介绍AMD Vivado™对Verilog硬件描述的合成支持语言 本章包括编码示例。从“coding”下载编码示例文件示例。 Verilog设计 复杂电路的设计通常采用自上而下的方法。 •设计过程的每个阶段都需要不同的规范级别。例如&#xff0c;在体系结构级别&…

成功解决‘OpenpyxlWriter’ object has no attribute ‘save’

成功解决‘OpenpyxlWriter’ object has no attribute ‘save’ &#x1f308; 个人主页&#xff1a;高斯小哥 &#x1f525; 高质量专栏&#xff1a;Matplotlib之旅&#xff1a;零基础精通数据可视化、Python基础【高质量合集】、PyTorch零基础入门教程&#x1f448; 希望得到…

力扣hot100题解(python版41-43题)

41、二叉树的层序遍历 给你二叉树的根节点 root &#xff0c;返回其节点值的 层序遍历 。 &#xff08;即逐层地&#xff0c;从左到右访问所有节点&#xff09;。 示例 1&#xff1a; 输入&#xff1a;root [3,9,20,null,null,15,7] 输出&#xff1a;[[3],[9,20],[15,7]]示例…