Request+正则表达式爬取猫眼电影数据
1、确定目标
爬取内容为:猫眼电影榜单数据。
猫眼电影https://maoyan.com/board/4
2、分析目标
切换下一页页面,观察url链接变化如下:
https://maoyan.com/board/4 # 第一页
https://maoyan.com/board/4?offset=10 #第二页
https://maoyan.com/board/4?offset=20 # 第三页
同时,检查页面元素,每一个电影信息都在dd元素内。
3、代码编写
3.1、获得页面数据
# 获得单页响应数据
def get_one_page(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'
}
try:
response = requests.get(url,headers=headers)
response.encoding = 'utf-8'
if response.status_code == 200:
print(response.text)
return response.text
return None
except RequestException:
return None
3.2、解析数据
# 数据解析器
def parse_one_page(html):
pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a'
+ '.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>'
+ '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S)
items = re.findall(pattern, html)
for item in items:
yield {
'title': item[2],
'index': item[0],
'image': item[1],
'actor': item[3].strip()[3:],
'time': item[4].strip()[5:],
'score': item[5] + item[6]
}
3.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()
3.4、主方法
def main(offset):
url = 'https://maoyan.com/board/4?offset=' + str(offset)
html = get_one_page(url)
for item in parse_one_page(html):
print(item)
write_to_file(item)
if __name__ == '__main__':
pool = Pool()
pool.map(main, [i * 10 for i in range(10)])
网友评论