如何使用python爬取知乎熱榜Top50數(shù)據(jù)
1、導(dǎo)入第三方庫
import urllib.request,urllib.error #請求網(wǎng)頁 from bs4 import BeautifulSoup # 解析數(shù)據(jù) import sqlite3 # 導(dǎo)入數(shù)據(jù)庫 import re # 正則表達(dá)式 import time # 獲取當(dāng)前時間
2、程序的主函數(shù)
def main(): # 聲明爬取網(wǎng)頁 baseurl = "https://www.zhihu.com/hot" # 爬取網(wǎng)頁 datalist = getData(baseurl) #保存數(shù)據(jù) dbname = time.strftime("%Y-%m-%d", time.localtime()) # dbpath = "zhihuTop50 " + dbname saveData(datalist,dbpath)
3、正則表達(dá)式匹配數(shù)據(jù)
#正則表達(dá)式 findlink = re.compile(r'<a class="css-hi1lih" href="(.*?)" rel="external nofollow" rel="external nofollow" ') #問題鏈接 findid = re.compile(r'<div class="css-blkmyu">(.*?)</div>') #問題排名 findtitle = re.compile(r'<h1 class="css-3yucnr">(.*?)</h1>') #問題標(biāo)題 findintroduce = re.compile(r'<div class="css-1o6sw4j">(.*?)</div>') #簡要介紹 findscore = re.compile(r'<div class="css-1iqwfle">(.*?)</div>') #熱門評分 findimg = re.compile(r'<img class="css-uw6cz9" src="(.*?)"/>') #文章配圖
4、程序運行結(jié)果
5、程序源代碼
import urllib.request,urllib.error from bs4 import BeautifulSoup import sqlite3 import re import time def main(): # 聲明爬取網(wǎng)頁 baseurl = "https://www.zhihu.com/hot" # 爬取網(wǎng)頁 datalist = getData(baseurl) #保存數(shù)據(jù) dbname = time.strftime("%Y-%m-%d", time.localtime()) dbpath = "zhihuTop50 " + dbname saveData(datalist,dbpath) print() #正則表達(dá)式 findlink = re.compile(r'<a class="css-hi1lih" href="(.*?)" rel="external nofollow" rel="external nofollow" ') #問題鏈接 findid = re.compile(r'<div class="css-blkmyu">(.*?)</div>') #問題排名 findtitle = re.compile(r'<h1 class="css-3yucnr">(.*?)</h1>') #問題標(biāo)題 findintroduce = re.compile(r'<div class="css-1o6sw4j">(.*?)</div>') #簡要介紹 findscore = re.compile(r'<div class="css-1iqwfle">(.*?)</div>') #熱門評分 findimg = re.compile(r'<img class="css-uw6cz9" src="(.*?)"/>') #文章配圖 def getData(baseurl): datalist = [] html = askURL(baseurl) # print(html) soup = BeautifulSoup(html,'html.parser') for item in soup.find_all('a',class_="css-hi1lih"): # print(item) data = [] item = str(item) Id = re.findall(findid,item) if(len(Id) == 0): Id = re.findall(r'<div class="css-mm8qdi">(.*?)</div>',item)[0] else: Id = Id[0] data.append(Id) # print(Id) Link = re.findall(findlink,item)[0] data.append(Link) # print(Link) Title = re.findall(findtitle,item)[0] data.append(Title) # print(Title) Introduce = re.findall(findintroduce,item) if(len(Introduce) == 0): Introduce = " " else:Introduce = Introduce[0] data.append(Introduce) # print(Introduce) Score = re.findall(findscore,item)[0] data.append(Score) # print(Score) Img = re.findall(findimg,item) if (len(Img) == 0): Img = " " else: Img = Img[0] data.append(Img) # print(Img) datalist.append(data) return datalist def askURL(baseurl): # 設(shè)置請求頭 head = { # "User-Agent": "Mozilla/5.0 (Windows NT 10.0;Win64;x64) AppleWebKit/537.36(KHTML, likeGecko) Chrome/80.0.3987.163Safari/537.36" "User-Agent": "Mozilla / 5.0(iPhone;CPUiPhoneOS13_2_3likeMacOSX) AppleWebKit / 605.1.15(KHTML, likeGecko) Version / 13.0.3Mobile / 15E148Safari / 604.1" } request = urllib.request.Request(baseurl, headers=head) html = "" try: response = urllib.request.urlopen(request) html = response.read().decode("utf-8") # print(html) except urllib.error.URLError as e: if hasattr(e, "code"): print(e.code) if hasattr(e, "reason"): print(e.reason) return html print() def saveData(datalist,dbpath): init_db(dbpath) conn = sqlite3.connect(dbpath) cur = conn.cursor() for data in datalist: sql = ''' insert into Top50( id,info_link,title,introduce,score,img) values("%s","%s","%s","%s","%s","%s")'''%(data[0],data[1],data[2],data[3],data[4],data[5]) print(sql) cur.execute(sql) conn.commit() cur.close() conn.close() def init_db(dbpath): sql = ''' create table Top50 ( id integer primary key autoincrement, info_link text, title text, introduce text, score text, img text ) ''' conn = sqlite3.connect(dbpath) cursor = conn.cursor() cursor.execute(sql) conn.commit() conn.close() if __name__ =="__main__": main()
到此這篇關(guān)于如何使用python爬取知乎熱榜Top50數(shù)據(jù)的文章就介紹到這了,更多相關(guān)python 爬取知乎內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Pycharm中pyqt工具配置(Qt Designer、PyUIC、PyRCC)
Pycharm中進(jìn)行擴(kuò)展工具設(shè)置,從而實現(xiàn)在pycharm中打開Qt Designer、Ui文件生成Py文件、資源文件生成Py文件三個功能,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07python 命令行傳入?yún)?shù)實現(xiàn)解析
這篇文章主要介紹了python 命令行傳入?yún)?shù)實現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08python實現(xiàn)對指定輸入的字符串逆序輸出的6種方法
這篇文章主要介紹了python實現(xiàn)對指定輸入的字符串逆序輸出的6種方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-04-04JavaScript實現(xiàn)一維數(shù)組轉(zhuǎn)化為二維數(shù)組
下面小編就為大家分享一篇JavaScript實現(xiàn)一維數(shù)組轉(zhuǎn)化為二維數(shù)組,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04使用pytorch進(jìn)行張量計算、自動求導(dǎo)和神經(jīng)網(wǎng)絡(luò)構(gòu)建功能
pytorch它是一個基于Python的開源深度學(xué)習(xí)框架,它提供了兩個核心功能:張量計算和自動求導(dǎo),這篇文章主要介紹了使用pytorch進(jìn)行張量計算、自動求導(dǎo)和神經(jīng)網(wǎng)絡(luò)構(gòu)建,需要的朋友可以參考下2023-04-04python中關(guān)于requests里的timeout()用法
這篇文章主要介紹了python中關(guān)于requests里的timeout()用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08