python使用re模塊爬取豆瓣Top250電影
爬?四步原理:
1.發(fā)送請求:requests
2.獲取相應(yīng)數(shù)據(jù):對方及其直接返回
3.解析并提取想要的數(shù)據(jù):re
4.保存提取后的數(shù)據(jù):with open()文件處理
爬?三步曲:
1.發(fā)送請求
2.解析數(shù)據(jù)
3.保存數(shù)據(jù)
注意:豆瓣網(wǎng)頁爬蟲必須使用請求頭,否則服務(wù)器不予返回?cái)?shù)據(jù)
import reimport requests# 爬?三部曲:# 1.獲取請求def get_data(url, headers): response = requests.get(url, headers=headers) # 如果爬取的是html文本就是用.text方法獲取文本數(shù)據(jù),如果爬取的是音視頻就用.content方法獲取二進(jìn)制流數(shù)據(jù) # print(response.text) # 獲取相應(yīng)文本,比如html代碼 return response.text# 2.解析數(shù)據(jù)def parser_data(text): # re.findall('正則表達(dá)式', '過濾的文本', re.S) # 匹配模式:re.S 全局模式 data = re.findall( ’<div class='item'>.*?<a href='http://www.gepszalag.com/bcjs/(.*?)' rel='external nofollow' >.*?<span class='title'>(.*?)</span>.*?<span property='v:average'>(.*?)</span>.*?<span>(.*?)人評價(jià)</span>’, text, re.S) for move_info in data: yield move_info# 3.保存數(shù)據(jù)def save_data(res_list_iter): with open('豆瓣TOP250.txt', 'a', encoding='utf-8') as f: for i in res_list_iter: move_page, move_title, move_score, move_evaluation = i # print(move_page, move_title, move_score, move_evaluation) str1 = f'電影名字:《{move_title}》 電影評分:{move_score} 電影評價(jià):{move_evaluation} 電影詳情頁:{move_page}n' f.write(str1)# 使用請求頭請求數(shù)據(jù)headers = { ’User-Agent’: ’Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36’}n = 0# 獲取10個(gè)鏈接for i in range(10): url = f'https://movie.douban.com/top250?start={n}&filter==' n += 25 text = get_data(url, headers) res_list_iter = parser_data(text) save_data(res_list_iter)
執(zhí)行結(jié)果:
以上就是python使用re模塊爬取豆瓣Top250電影的詳細(xì)內(nèi)容,更多關(guān)于python 爬取豆瓣電影的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)2. ASP.NET MVC實(shí)現(xiàn)區(qū)域或城市選擇3. 使用EF Code First搭建簡易ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫遷移4. HTML <!DOCTYPE> 標(biāo)簽5. php中創(chuàng)建字符串的變量實(shí)例講解6. 解決idea使用過程中讓你覺得不爽的一些問題(小結(jié))7. IDEA讓包分層顯示的實(shí)現(xiàn)方式8. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案9. HTML5 Canvas繪制圖形從入門到精通10. CSS3+Js實(shí)現(xiàn)響應(yīng)式導(dǎo)航條
