抓取猫眼电影排行
先抓取猫眼网页,运用正则表达式截取字符串,获取前100个电影信息:
- 1-10链接:https://maoyan.com/board/4
- 11-20链接:https://maoyan.com/board/4?offset=10
- 21-30链接:https://maoyan.com/board/4?offset=20
import requests
def get_page(url):
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"
}
response = requests.get(url,headers=headers)
if response.status_code==200:
return response.text
return None
def main():
url='https://maoyan.com/board/4'
html=get_page(url)
print(html)
main()
以上就取了第一页的网页源码,下面进行正则提取【通过Network查看源码】:
- 获取排名信息,在dd节点下的class为board-index的i节点:
<dd>.*?board-index.*>(.*?)</i>
- 提取图片链接,img节点下的data-src属性:
<dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)"
- 提取电影名,p节点下的class为name的a节点:
<dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?name.*?a.*?>(.*?)</a>
- 提取主演,时间,评分等:
<dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?name.*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>.*?fraction.*?>(.*?)</i>.*?</dd>
提取100条电影信息:
import requests
import re
import json
import time
def get_page(url):
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"
}
response = requests.get(url,headers=headers)
if response.status_code==200:
return response.text
return None
def parse_page(html):
pattern = re.compile(
'<dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?name.*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>.*?fraction.*?>(.*?)</i>.*?</dd>',
re.S)
items = re.findall(pattern,html)
#整理信息,并组成字典
for it in items:
yield {
'index':it[0],
'image':it[1],
'title':it[2].strip(),#删除头尾空格换行符
'actor':it[3].strip()[3:] if len(it[3])>3 else '',
'data':it[4].strip()[5:] if len(it[4])>5 else '',
'score':it[5].strip() + it[6].strip()
}
def write_file(content):
with open('result.txt','a',encoding='utf-8') as f:
f.write(json.dumps(content,ensure_ascii=False)+'\n')
def main(offset):
url='https://maoyan.com/board/4?offset='+str(offset)
html=get_page(url)
for item in parse_page(html):
print(item)
write_file(item)
if __name__=='__main__':
for i in range(10):
main(offset=i*10)
#time.sleep(1)
运行结尾为【只举例3条】:
{'index': '1', 'image': 'https://p1.meituan.net/movie/20803f59291c47e1e116c11963ce019e68711.jpg@160w_220h_1e_1c', 'title': '霸王别姬', 'actor': '张国荣,张丰毅,巩俐', 'data': '1993-01-01', 'score': '9.5'}
{'index': '2', 'image': 'https://p0.meituan.net/movie/283292171619cdfd5b240c8fd093f1eb255670.jpg@160w_220h_1e_1c', 'title': '肖申克的救赎', 'actor': '蒂姆·罗宾斯,摩根·弗里曼,鲍勃·冈顿', 'data': '1994-10-14(美国)', 'score': '9.5'}
{'index': '3', 'image': 'https://p0.meituan.net/movie/289f98ceaa8a0ae737d3dc01cd05ab052213631.jpg@160w_220h_1e_1c', 'title': '罗马假日', 'actor': '格利高里·派克,奥黛丽·赫本,埃迪·艾伯特', 'data': '1953-09-02(美国)', 'score': '9.1'}