第十五天-爬蟲項目實戰

目錄

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.pswp.cn/news/713580.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/713580.shtml
英文地址,請注明出處:http://en.pswp.cn/news/713580.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python66-Python的循環之常用工具函數

使用zip()函數可以把兩個列表“壓縮”成一個zip對象(可迭代對象),這樣就可以使用一個循環并行遍歷兩個列表。為了測試 zip()函數的功能,我們可以先在交互式解釋器中“試驗”一下該函數的功能。 # !/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2024/01# @Author : …

元數據優化:提升您的網站在搜索引擎中的表現

前言 在之前的文章中,我們探討了如何通過超鏈接來提高用戶在網站的使用體驗。本篇將聚焦于元數據的優化,揭示它如何成為提升網站曝光率和點擊率的秘密武器。 一、介紹 元數據,或稱之為數據的數據,在網頁開發中占據著不可忽視的角…

IPD MM流程之業務策略工具:安索夫矩陣

IPD市場管理流程,華為內部稱為“MM流程”(Market Management,MM)。華為市場管理是通過對市場和細分市場的分析,制定細分市場的策略,形成商業計劃,把商業計劃落實在日常工作當中。MM流程其中一個…

git根據文件改動將文件自動添加到緩沖區

你需要修改以下腳本中的 use_cca: false 部分 #!/bin/bash# 獲取所有已修改但未暫存的文件 files$(git diff --name-only)for file in $files; do# 檢查文件中是否存在"use_cca: false"if grep -q "use_cca: false" "$file"; thenecho "Ad…

3.1線程作業

1.要求定義一個全局變量char buf"1234567",創建兩個線程,不考慮退出條件。 a.A線程循環打印buf字符串, b.B線程循環倒置buf字符串,即buf中本來存儲1234567,倒置后buf中存儲7654321.B線程中不打印!! c.倒置…

qt5-入門-使用拖動方式創建Dialog

參考: C GUI Programming with Qt 4, Second Edition 本地環境: win10專業版,64位,Qt5.12 目錄 實現效果基本流程逐步實操1)創建和初始化子部件2)把子部件放進布局中3)設置tab順序4&#xff09…

jstat命令查看jvm的GC信息

文章目錄 前言jstat命令查看jvm的GC信息1. 概述2. 應用堆內存水位閥值大小怎么確定3. 使用 jps 命令查看 Java 進程的進程號(PID)![在這里插入圖片描述](https://img-blog.csdnimg.cn/direct/5097401443314e9d808a83b694dbc6e5.png)4. jstat用法5. 類加載…

UE4 Niagara 關卡3.1官方案例解析二

自己嘗試做做,打亂順序 1、新建空的niagara system,添加空的發射器。更換渲染器為網格體渲染器并添加網格體。 2、發射器更新里面添加Spawn Rate,發射個粒子看看 效果圖: 3、采樣靜態網格體,網格體粒子出生于靜態網格…

【排序算法】基數排序

一:基本概念 1.1 基數排序(桶排序)介紹 基數排序(radix sort)屬于“分配式排序”(distribution sort),又稱“桶子法”(bucket sort)或bin sort,顧名思義,它是…

【圖說】電腦發展史

免責聲明:文中有一些圖片來源自網絡,如有版權請通知我刪除,謝謝! “結繩記事”是計算的開端 如果說“結繩記事”僅是計數,那么“算籌”就是真正的計算工具 算盤也是我們老祖宗的杰出發明,最擅長“加減乘除”,包括但不限于乘方、開方、對數等。還能進行開發智力的“珠心算…

鼠標失靈怎么辦?電腦出現鼠標失靈的詳細處理方法介紹

無論是筆記本電腦還是臺式機電腦,鼠標是必不可少的外設之一,而我們在使用電腦的過程中,經常回遇到鼠標突然失靈了,不聽使喚,控制不了,接下小編來與大家一起分享,遇到這種情況我們該怎么辦 有時…

C語言學習筆記(二)

C語言學習 學習筆記(一) 學習筆記(二) 文章目錄 C語言學習一、C語言中的數據類型進制二進制八進制十六進制進制轉換表 單位換算尋址 數據類型基本類型整數類型整數的有符號和無符號實數類型字符型 構造類型指針類型空類型總結 常量直接常量符號常量轉義符 符號常量…

Python并發編程:多線程-GIL全局解釋器鎖

一 引子 在Cpython解釋器中,同一個進程下開啟的多線程,同一時刻只能有一個線程執行,無法利用多核優勢首先:需要明確的一點是GIL并不是Python的特性,它是在實現Python解析器(CPython)時所引入的一個概念。就好比c是一套…

協議(網絡協議)

HTTP/HTTPS 協議 HTTP 實際上是個縮寫,英文全稱是:Hyper Text Transfer Protocol (超文本傳輸協議)。 最常用的網頁(也叫web頁)就是一種超文本的具體表現形式。HTTPS (全稱:Hyper …

美團-放水果

題目: 放水果 把M個相同的水果放在N個同樣的盤子里,允許有的盤子空著不放,問不同的放法數K是多少?請注意,5,1,1和1,5,1 是同一種放法。輸入描述 第一行是測試數據的數目…

【Spring】19 @Autowired注解使用詳解

文章目錄 構造函數注入Setter方法注入字段注入數組和集合注入特殊情況處理特殊接口類型的注入異常處理結語 Spring 框架的 Autowired 注解是實現依賴注入的一種強大而靈活的方式。在本文中,我們將介紹 Autowired 注解的多種用法,包括構造函數、setter方法…

ICASSP2024 | ICMC-ASR 車載多通道語音識別挑戰賽總結

為促進駕駛場景中語音處理和識別研究,在ISCSLP 2022上成功舉辦智能駕駛座艙語音識別挑戰 (ICSRC)的基礎上,西工大音頻語音與語言處理研究組 (ASLPNPU)聯合理想汽車、希爾貝殼、WeNet社區、字節、微軟、天津大學、南洋理工大學以及中國信息通信研究院等多…

EMO在哪體驗?阿里對口型視頻生成工具EMO下載地址?阿里巴巴新模型EMO的技術原理

這幾天,阿里的對口型視頻生成工具EMO火了。根據官方宣傳,EMO只需要上傳一張圖片和一段音頻就可以一鍵生成對口型視頻,而且視頻中的嘴型還可以與聲音匹配。這項技術支持多語言、對話、唱歌以及快速語速的適配,但也可能成為制造虛假…

pip降級在pycharm中

PyCharm依賴于"–build-dir"參數安裝第三方庫,但該參數在最新的23.0版pip中已刪除 解決辦法就是降級pip,PyCharm中選擇File,找到編譯器,點擊pip,勾選對應版本即可 或者在cmd中執行運行python -m pip install…

基于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如果上面執行命令后…