第十五天-爬虫项目实战

目录

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://www.rhkb.cn/news/267092.html

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

相关文章

修改docker默认存储位置【高版本的docker】

一、修改docker默认存储位置 1、停服务 systemctl stop docker 2、修改/etc/docker/daemon.json添加新的dcoker路径 如"data-root": "/mnt/hdd1/docker" 3、保存后重启服务:systemctl restart docker 二、其他服务的命令 systemctl disab…

基于centos的linux上docker安装,及mysql、redis等应用在docker容器中的安装

Docker环境安装 安装yum-utils: yum install ‐y yum‐utils device‐mapper‐persistent‐data lvm2为yum源添加docker仓库位置: yum‐config‐manager ‐‐add‐repo https://download.docker.com/linux/centos/docker‐ce.repo如果上面执行命令后…

hippy 调试demo运行联调-mac环境准备篇

适用对于终端编译环境不熟悉的人看,仅mac端 hippy 调试文档官网地址 前提:请使用node16 联调预览效果图: 编译iOS Demo环境准备 未跑通,待补充 编译Android Demo环境准备 1、正常安装Android Studio 2、下载Android NDK&a…

群控代理IP搭建教程:打造一流的网络爬虫

目录 前言 一、什么是群控代理IP? 二、搭建群控代理IP的步骤 1. 获取代理IP资源 2. 配置代理IP池 3. 选择代理IP策略 4. 编写代理IP设置代码 5. 异常处理 三、总结 前言 群控代理IP是一种常用于网络爬虫的技术,通过使用多个代理IP实现并发请求…

力扣SQL50 产品销售分析 I 查询

Problem: 1068. 产品销售分析 I 思路 left join on:左连接 Code select p.product_name, s.year, s.price from Sales s left join Product p on s.product_id p.product_id

力扣SQL50 无效的推文 查询

Problem: 1683. 无效的推文 思路 👨‍🏫 参考 char_length(str):计算 str 的字符长度length(str):计算 str 的字节长度 Code select tweet_id from Tweets where char_length(content) > 15;

【Vue】更换浏览器默认 logo

更换浏览器默认logo为自定义图片 一. 浏览器默认 logo二. 替换为自定义logo三. 步骤3.1 转换大小3.1.1 查看图片尺寸3.1.2 修改尺寸(为32px 32px) 3.2 替换成功 一. 浏览器默认 logo 二. 替换为自定义logo 三. 步骤 3.1 转换大小 将自定义 logo 转为323…

二叉搜索树在线OJ题讲解

二叉树创建字符串 我们首先进行题目的解读: 大概意思就是用()把每个节点的值给括起来,然后再经过一系列的省略的来得到最后的结果 大家仔细观察题目给出的列子就可以发现,其实这个题目可以大致分为三种情况&#xff1…

贝叶斯定理与条件独立假设:朴素贝叶斯分类方法深度解读

今天给大家分享的是朴素贝叶斯算法,这个算法在实际使用中不是很多,因为现在很多算法已经发展的很好,性能上也比朴素贝叶斯算法的好很多,因此在实际中我们其实看到在实际应用中朴素贝叶斯算法的使用已经比较少,即使出现…

高级语言期末2008级A卷(计算机学院)

1.编bool型函数&#xff0c;判断二维空间中的某点是否优于另一点。优于关系定义为&#xff1a;在二维空间中&#xff0c;某点&#xff08;A1&#xff0c;A2&#xff09;优于&#xff08;B1&#xff0c;B2&#xff09;&#xff0c;当且仅当A1>B1,A2>B2 #include <stdi…

【C++进阶】哈希(万字详解)—— 学习篇(上)

&#x1f387;C学习历程&#xff1a;入门 博客主页&#xff1a;一起去看日落吗持续分享博主的C学习历程博主的能力有限&#xff0c;出现错误希望大家不吝赐教分享给大家一句我很喜欢的话&#xff1a; 也许你现在做的事情&#xff0c;暂时看不到成果&#xff0c;但不要忘记&…

Tomcat部署Web服务器及基础功能配置

前言 Tomcat作为一款网站服务器&#xff0c;目前市面上Java程序使用的比较多&#xff0c;作为运维工人&#xff0c;有必要了解一款如何去运行Java环境的网站服务。 目录 一、Java相关介绍 1. Java历史 2. Java跨平台服务 3. Java实现动态网页功能 3.1 servelt 3.2 jsp …

python统计分析——广义线性模型的评估

参考资料&#xff1a;用python动手学统计学 残差是表现数据与模型不契合的程度的重要指标。 1、导入库 # 导入库 # 用于数值计算的库 import numpy as np import pandas as pd import scipy as sp from scipy import stats # 导入绘图的库 import matplotlib.pyplot as plt i…

AcWing 466. 回文日期

先贴个题目&#xff1a; 以及原题链接&#xff1a;466. 回文日期 - AcWing题库https://www.acwing.com/problem/content/468/ 这题乍一看有点恶心&#xff0c;如果枚举日期还要判断合法性&#xff0c;然后每个日期再判断是不是回文&#xff0c;即麻烦&#xff0c;时间复杂度又高…

day07_分类管理EasyExcel品牌管理

文章目录 1 分类管理1.1 菜单添加1.2 表结构介绍1.3 页面制作1.4 列表查询1.4.1 需求分析1.4.2 后端接口CategoryCategoryControllerCategoryServiceCategoryMapperCategoryMapper.xml 1.4.3 前端对接category.jscategory.vue 2 EasyExcel2.1 数据导入导出意义2.2 EasyExcel简介…

本地maven库缓存导入私库

为了加速编译代码&#xff0c;想将本地maven缓存导入内网私库使用。 脚本网上搜的 #!/bin/bash # copy and run this script to the root of the repository directory containing files # this script attempts to exclude uploading itself explicitly so the script name …

物体检测-系列教程19:YOLOV5 源码解析9 (Focus模块、Model类构造函数)

&#x1f60e;&#x1f60e;&#x1f60e;物体检测-系列教程 总目录 有任何问题欢迎在下面留言 本篇文章的代码运行界面均在Pycharm中进行 本篇文章配套的代码资源已经上传 点我下载源码 13、Focus模块 13.1 基本流程 原始输入图像的格式为&#xff1a;tensor: float32[1,3,64…

Unity(第十八部)物理力学,碰撞,触发、关节和材质

1、重力 刚体组件 英文中文描述RigidBody刚体组件physics->rigidbody &#xff0c;刚体组件使一个物体有了质量&#xff0c;重力等。&#xff0c;use gravity 勾选后&#xff0c;物体才会受到重力&#xff0c;会自动下落&#xff0c;取消勾选就不会。&#xff0c;&#xf…

Unity中URP下实现水体(水面反射)

文章目录 前言一、原理1、法一&#xff1a;使用立方体纹理 CubeMap&#xff0c;作为反射纹理使用2、法二&#xff1a;使用反射探针生成环境反射图&#xff0c;所谓反射的采样纹理 二、实现水面反射1、定义和申明CubeMap2、反射向量需要什么3、计算 N ⃗ \vec{N} N 4、计算 V ⃗…

【力扣白嫖日记】550.游戏玩法分析IV

前言 练习sql语句&#xff0c;所有题目来自于力扣&#xff08;https://leetcode.cn/problemset/database/&#xff09;的免费数据库练习题。 今日题目&#xff1a; 550.游戏玩法分析IV 表&#xff1a;Activity 列名类型player_idintdevice_idintevent_datedategames_played…