這篇文章主要介紹Python如何爬取愛(ài)奇藝電影信息,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
一,使用庫(kù)
1.requests
2.re
3.json
二,抓取html文件
def get_page(url): response = requests.get(url) if response.status_code == 200: return response.text return None
三,解析html文件
我們需要的電影信息的部分如下圖(評(píng)分,片名,主演):
抓取到的html文件對(duì)應(yīng)的代碼:
可以分析出,每部電影的信息都在一個(gè)<li>標(biāo)簽內(nèi),用正則表達(dá)式解析:
def parse_page(html): pattern = re.compile('<li.*?qy-mod-li.*?text-score">(.*?)<.*?title.*?>(.*?)<.*?title.*?>(.*?)<', re.S) items = re.findall(pattern, html) for item in items:#轉(zhuǎn)換為字典形式保存 yield { 'score': item[0], 'name': item[1], 'actor': item[2].strip()[3:]#將‘主演:'去掉 }
四,寫(xiě)入文件
def write_to_file(content): with open('result.txt', 'a', encoding='utf-8')as f: f.write(json.dumps(content, ensure_ascii=False) + '\n')#將字典格式轉(zhuǎn)換為字符串加以保存,并設(shè)置中文格式 f.close()
五,調(diào)用函數(shù)
def main(): url = 'https://list.iqiyi.com/www/1/-------------8-1-1-iqiyi--.html' html = get_page(url) for item in parse_page(html): print(item) write_to_file(item)
六,運(yùn)行結(jié)果
七,完整代碼
import json import requests import re # 抓取html文件 # 解析html文件 # 存儲(chǔ)文件 def get_page(url): response = requests.get(url) if response.status_code == 200: return response.text return None def parse_page(html): pattern = re.compile('<li.*?qy-mod-li.*?text-score">(.*?)<.*?title.*?>(.*?)<.*?title.*?>(.*?)<', re.S) items = re.findall(pattern, html) for item in items: yield { 'score': item[0], 'name': item[1], 'actor': item[2].strip()[3:] } def write_to_file(content): with open('result.txt', 'a', encoding='utf-8')as f: f.write(json.dumps(content, ensure_ascii=False) + '\n') f.close() def main(): url = 'https://list.iqiyi.com/www/1/-------------8-1-1-iqiyi--.html' html = get_page(url) for item in parse_page(html): print(item) write_to_file(item) if __name__ == '__main__': main()
以上是“Python如何爬取愛(ài)奇藝電影信息”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
分享題目:Python如何爬取愛(ài)奇藝電影信息-創(chuàng)新互聯(lián)
標(biāo)題來(lái)源:http://www.yijiale78.com/article32/hhopc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、營(yíng)銷(xiāo)型網(wǎng)站建設(shè)、網(wǎng)站排名、App開(kāi)發(fā)、網(wǎng)站制作、網(wǎng)站設(shè)計(jì)公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容