Python7個爬蟲小案例詳解(附源碼)上篇
本次的7個python爬蟲小案例涉及到了re正則、xpath、beautiful soup、selenium等知識點,非常適合剛?cè)腴Tpython爬蟲的小伙伴參考學(xué)習(xí)。
前言
關(guān)于Python7個爬蟲小案例的文章分為三篇,本篇為上篇,共兩題,其余兩篇內(nèi)容請關(guān)注!
題目一:
使用正則表達(dá)式和文件操作爬取并保存“百度貼吧”某帖子全部內(nèi)容(該帖不少于5頁)
本次選取的是百度貼吧中的NBA吧中的一篇帖子,帖子標(biāo)題是“克萊和哈登,誰歷史地位更高”。爬取的目標(biāo)是帖子里面的回復(fù)內(nèi)容。
源程序和關(guān)鍵結(jié)果截圖:
import csv import requests import re import time def main(page): url = f'https://tieba.baidu.com/p/7882177660?pn={page}' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36' } resp = requests.get(url,headers=headers) html = resp.text # 評論內(nèi)容 comments = re.findall('style="display:;"> (.*?)</div>',html) # 評論用戶 users = re.findall('class="p_author_name j_user_card" href=".*?" rel="external nofollow" target="_blank">(.*?)</a>',html) # 評論時間 comment_times = re.findall('樓</span><span class="tail-info">(.*?)</span><div',html) for u,c,t in zip(users,comments,comment_times): # 篩選數(shù)據(jù),過濾掉異常數(shù)據(jù) if 'img' in c or 'div' in c or len(u)>50: continue csvwriter.writerow((u,t,c)) print(u,t,c) print(f'第{page}頁爬取完畢') if __name__ == '__main__': with open('01.csv','a',encoding='utf-8')as f: csvwriter = csv.writer(f) csvwriter.writerow(('評論用戶','評論時間','評論內(nèi)容')) for page in range(1,8): # 爬取前7頁的內(nèi)容 main(page) time.sleep(2)
題目二:
實現(xiàn)多線程爬蟲爬取某小說部分章節(jié)內(nèi)容并以數(shù)據(jù)庫存儲(不少于10個章節(jié))
本次選取的小說網(wǎng)址是全本小說網(wǎng)https://www.qb5.tw/,這里我們選取第一篇小說進(jìn)行爬取
然后通過分析網(wǎng)頁源代碼分析每章小說的鏈接
找到鏈接的位置后,我們使用Xpath來進(jìn)行鏈接和每一章標(biāo)題的提取
在這里,因為涉及到多次使用requests發(fā)送請求,所以這里我們把它封裝成一個函數(shù),便于后面的使用
每一章的鏈接獲取后,我們開始進(jìn)入小說章節(jié)內(nèi)容頁面進(jìn)行分析
通過網(wǎng)頁分析,小說內(nèi)容都在網(wǎng)頁源代碼中,屬于靜態(tài)數(shù)據(jù)
這里我們選用re正則表達(dá)式進(jìn)行數(shù)據(jù)提取,并對最后的結(jié)果進(jìn)行清洗
然后我們需要將數(shù)據(jù)保存到數(shù)據(jù)庫中,這里我將爬取的數(shù)據(jù)存儲到mysql數(shù)據(jù)庫中,先封住一下數(shù)據(jù)庫的操作
接著將爬取到是數(shù)據(jù)進(jìn)行保存
最后一步就是使用多線程來提高爬蟲效率,這里我們創(chuàng)建了5個線程的線程池
源代碼及結(jié)果截圖:
import requests from lxml import etree import re import pymysql from time import sleep from concurrent.futures import ThreadPoolExecutor def get_conn(): # 創(chuàng)建連接 conn = pymysql.connect(host="127.0.0.1", user="root", password="root", db="novels", charset="utf8") # 創(chuàng)建游標(biāo) cursor = conn.cursor() return conn, cursor def close_conn(conn, cursor): cursor.close() conn.close() def get_xpath_resp(url): headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'} resp = requests.get(url, headers=headers) tree = etree.HTML(resp.text) # 用etree解析html return tree,resp def get_chapters(url): tree,_ = get_xpath_resp(url) # 獲取小說名字 novel_name = tree.xpath('//*[@id="info"]/h1/text()')[0] # 獲取小說數(shù)據(jù)節(jié)點 dds = tree.xpath('/html/body/div[4]/dl/dd') title_list = [] link_list = [] for d in dds[:15]: title = d.xpath('./a/text()')[0] # 章節(jié)標(biāo)題 title_list.append(title) link = d.xpath('./a/@href')[0] # 章節(jié)鏈接 chapter_url = url +link # 構(gòu)造完整鏈接 link_list.append(chapter_url) return title_list,link_list,novel_name def get_content(novel_name,title,url): try: cursor = None conn = None conn, cursor = get_conn() # 插入數(shù)據(jù)的sql sql = 'INSERT INTO novel(novel_name,chapter_name,content) VALUES(%s,%s,%s)' tree,resp = get_xpath_resp(url) # 獲取內(nèi)容 content = re.findall('<div id="content">(.*?)</div>',resp.text)[0] # 對內(nèi)容進(jìn)行清洗 content = content.replace('<br />','\n').replace(' ',' ').replace('全本小說網(wǎng) www.qb5.tw,最快更新<a rel="external nofollow" >宇宙職業(yè)選手</a>最新章節(jié)!<br><br>','') print(title,content) cursor.execute(sql,[novel_name,title,content]) # 插入數(shù)據(jù) conn.commit() # 提交事務(wù)保存數(shù)據(jù) except: pass finally: sleep(2) close_conn(conn, cursor) # 關(guān)閉數(shù)據(jù)庫 if __name__ == '__main__': # 獲取小說名字,標(biāo)題鏈接,章節(jié)名稱 title_list, link_list, novel_name = get_chapters('https://www.qb5.tw/book_116659/') with ThreadPoolExecutor(5) as t: # 創(chuàng)建5個線程 for title,link in zip(title_list,link_list): t.submit(get_content, novel_name,title,link) # 啟動線程
到此這篇關(guān)于Python7個爬蟲小案例詳解(附源碼)上篇的文章就介紹到這了,其他兩個部分的內(nèi)容(中、下篇)請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python7個爬蟲小案例詳解(附源碼)下篇
- Python7個爬蟲小案例詳解(附源碼)中篇
- 利用Python爬蟲爬取金融期貨數(shù)據(jù)的案例分析
- Python爬蟲采集Tripadvisor數(shù)據(jù)案例實現(xiàn)
- Python?Ajax爬蟲案例分享
- Python爬蟲入門案例之爬取去哪兒旅游景點攻略以及可視化分析
- Python爬蟲入門案例之爬取二手房源數(shù)據(jù)
- Python爬蟲入門案例之回車桌面壁紙網(wǎng)美女圖片采集
- Python爬蟲之Scrapy環(huán)境搭建案例教程
- 用Python爬蟲破解滑動驗證碼的案例解析
- python爬蟲系列網(wǎng)絡(luò)請求案例詳解
- python爬蟲破解字體加密案例詳解
- python爬蟲線程池案例詳解(梨視頻短視頻爬取)
- python爬蟲scrapy框架的梨視頻案例解析
- python爬蟲利器之requests庫的用法(超全面的爬取網(wǎng)頁案例)
- Python爬蟲實戰(zhàn)案例之爬取喜馬拉雅音頻數(shù)據(jù)詳解
- Python爬蟲Scrapy框架CrawlSpider原理及使用案例
- Python爬蟲之對CSDN榜單進(jìn)行分析
相關(guān)文章
Python深度學(xué)習(xí)實戰(zhàn)PyQt5安裝與環(huán)境配置過程詳解
本系列面向 Python 小白,從零開始實戰(zhàn)解說應(yīng)用 QtDesigner 進(jìn)行 PyQt5 的項目實戰(zhàn)。什么叫從零開始?從軟件安裝、環(huán)境配置開始。不跳過一個細(xì)節(jié),不漏掉一行代碼,不省略一個例圖2021-10-10python使用pymongo與MongoDB基本交互操作示例
這篇文章主要介紹了python使用pymongo與MongoDB基本交互操作,結(jié)合實例形式詳細(xì)分析了python基于pymongo庫實現(xiàn)與MongoDB基本交互相關(guān)操作技巧與注意事項,需要的朋友可以參考下2020-04-04Tensorflow 訓(xùn)練自己的數(shù)據(jù)集將數(shù)據(jù)直接導(dǎo)入到內(nèi)存
這篇文章主要介紹了Tensorflow 訓(xùn)練自己的數(shù)據(jù)集將數(shù)據(jù)直接導(dǎo)入到內(nèi)存,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06Python pandas自定義函數(shù)的使用方法示例
這篇文章主要介紹了Python pandas自定義函數(shù)的使用方法,結(jié)合實例形式分析了pandas模塊相關(guān)自定義函數(shù)數(shù)值運算操作技巧,需要的朋友可以參考下2019-11-11淺談django model的get和filter方法的區(qū)別(必看篇)
下面小編就為大家?guī)硪黄獪\談django model的get和filter方法的區(qū)別(必看篇)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05Python 通過監(jiān)聽端口實現(xiàn)唯一腳本運行方式
這篇文章主要介紹了Python 通過監(jiān)聽端口實現(xiàn)唯一腳本運行方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05