榜单规则:将猫眼电影库中的经典影片,按照评分和评分人数从高到低综合排序取前100名,每天上午10点更新。相关数据来源于“猫眼电影库”。
爬取步骤:
通过requests库获取网页源代码;
通过re正则匹配,简单粗暴;
结果保存
top100榜单url是有规律的,https://maoyan.com/board/4?offset=,offset后接0,10,。。。,90.循环抓取即可。
需要抓取的元素
正则匹配表达式
pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?<img.*?alt.*?src="(.*?)".*?</a>.*?data-act.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S)
完整代码
import requests
from requests.exceptions import RequestException
import re
import json
def get_page(url):
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
return None
except RequestException:
return None
def get_data(html):
pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?<img.*?alt.*?src="(.*?)".*?</a>.*?data-act.*?>(.*?)'
+ '</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S)
items = re.findall(pattern, html)
for item in items:
yield{
'index': item[0],
'image': item[1],
'name': item[2].strip(),
'actor': item[3].split(':')[-1].strip(),
'time': item[4].split(':')[-1].strip(),
'score': item[5] + item[6]
}
if __name__ == '__main__':
base_url = 'https://maoyan.com/board/4?offset='
for i in range(10):
url = base_url + str(i*10)
items = get_data(get_page(url))
with open('D:\logs\猫眼.txt','a', encoding='utf-8') as f:
for item in items:
f.writelines(json.dumps(item, ensure_ascii=False))
猜你可能喜欢