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://m.propowerdrill.cn/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. ASP.NET MVC使用Boostrap實(shí)現(xiàn)產(chǎn)品展示、查詢、排序、分頁(yè)2. ASP.NET MVC使用JSAjaxFileUploader插件實(shí)現(xiàn)單文件上傳3. 使用ajax跨域調(diào)用springboot框架的api傳輸文件4. PHP數(shù)組操作詳細(xì)解釋5. 使用AJAX實(shí)現(xiàn)上傳文件6. Python dict的常用方法示例代碼7. Vue實(shí)現(xiàn)todo應(yīng)用的示例8. Android實(shí)現(xiàn)下載進(jìn)度條效果9. vue中v-for循環(huán)選中點(diǎn)擊的元素并對(duì)該元素添加樣式操作10. 解決python logging遇到的坑 日志重復(fù)打印問(wèn)題
