Python爬取愛奇藝電影信息代碼實例
更新時間:2019年11月26日 09:36:09 作者:陳暢
這篇文章主要介紹了Python爬取愛奇藝電影信息代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
這篇文章主要介紹了Python爬取愛奇藝電影信息代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
一,使用庫
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文件
我們需要的電影信息的部分如下圖(評分,片名,主演):

抓取到的html文件對應的代碼:

可以分析出,每部電影的信息都在一個<li>標簽內,用正則表達式解析:
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)
六,運行結果


七,完整代碼
import json
import requests
import re
# 抓取html文件
# 解析html文件
# 存儲文件
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爬蟲入門教程01之爬取豆瓣Top電影
- python使用re模塊爬取豆瓣Top250電影
- 用Python 爬取貓眼電影數據分析《無名之輩》
- Python利用Scrapy框架爬取豆瓣電影示例
- Python實現的爬取豆瓣電影信息功能案例
- python實現的爬取電影下載鏈接功能示例
- Python使用mongodb保存爬取豆瓣電影的數據過程解析
- 詳解Python爬取并下載《電影天堂》3千多部電影
- Python爬蟲——爬取豆瓣電影Top250代碼實例
- python使用BeautifulSoup與正則表達式爬取時光網不同地區(qū)top100電影并對比
- python使用requests模塊實現爬取電影天堂最新電影信息
- 一個簡單的python爬蟲程序 爬取豆瓣熱度Top100以內的電影信息
- python正則表達式爬取貓眼電影top100
- 教你怎么用python爬取愛奇藝熱門電影
相關文章
Python中的shape[0]、shape[1]和shape[-1]使用方法
shape函數是Numpy中的函數,它的功能是讀取矩陣的長度,比如shape[0]就是讀取矩陣第一維度的長度,這篇文章主要介紹了Python中的shape[0]、shape[1]和shape[-1]使用方法,需要的朋友可以參考下2023-07-07
Python使用回溯法子集樹模板獲取最長公共子序列(LCS)的方法
這篇文章主要介紹了Python使用回溯法子集樹模板獲取最長公共子序列(LCS)的方法,簡單描述了最長公共子序列問題并結合實例形式分析了Python基于回溯法子集樹模板獲取最長公共子序列的操作步驟與相關注意事項,需要的朋友可以參考下2017-09-09

