python使用re模塊爬取豆瓣Top250電影
爬?四步原理:
1.發(fā)送請(qǐng)求:requests
2.獲取相應(yīng)數(shù)據(jù):對(duì)方及其直接返回
3.解析并提取想要的數(shù)據(jù):re
4.保存提取后的數(shù)據(jù):with open()文件處理
爬?三步曲:
1.發(fā)送請(qǐng)求
2.解析數(shù)據(jù)
3.保存數(shù)據(jù)
注意:豆瓣網(wǎng)頁(yè)爬蟲(chóng)必須使用請(qǐng)求頭,否則服務(wù)器不予返回?cái)?shù)據(jù)
import reimport requests# 爬?三部曲:# 1.獲取請(qǐng)求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á)式', '過(guò)濾的文本', re.S) # 匹配模式:re.S 全局模式 data = re.findall( ’<div class='item'>.*?<a href='http://www.intensediesel.com/bcjs/(.*?)' rel='external nofollow' >.*?<span class='title'>(.*?)</span>.*?<span property='v:average'>(.*?)</span>.*?<span>(.*?)人評(píng)價(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}》 電影評(píng)分:{move_score} 電影評(píng)價(jià):{move_evaluation} 電影詳情頁(yè):{move_page}n' f.write(str1)# 使用請(qǐng)求頭請(qǐng)求數(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 爬取豆瓣電影的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. python如何實(shí)現(xiàn)word批量轉(zhuǎn)HTML2. 利用單元測(cè)試對(duì)PHP代碼進(jìn)行檢查3. python excel和yaml文件的讀取封裝4. python3實(shí)現(xiàn)往mysql中插入datetime類(lèi)型的數(shù)據(jù)5. moment轉(zhuǎn)化時(shí)間戳出現(xiàn)Invalid Date的問(wèn)題及解決6. Java8內(nèi)存模型PermGen Metaspace實(shí)例解析7. python爬蟲(chóng)實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊8. 如何對(duì)php程序中的常見(jiàn)漏洞進(jìn)行攻擊9. python 利用toapi庫(kù)自動(dòng)生成api10. 詳解Python利用configparser對(duì)配置文件進(jìn)行讀寫(xiě)操作
