import json
import re
import requests
def get_one_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 item in items:
# 使用 yield 的好处,每迭代一次,会直接返回那一次的结果,下次迭代再进循环,在输出,然后再进行循环,并且可以生成词典,如下:
yield {
'index': item[0],
'image': item[1],
'title': item[2].strip(),
'actor': item[3].strip()[3:] if len(item[3]) > 3 else '',
'time': item[4].strip()[5:] if len(item[4]) > 5 else '',
'score': item[5].strip() + item[6].strip()
}
def main():
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac 05 X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/52.0.2743.116 Safari/537.36'
}
url = 'http://maoyan.com/board/4'
response = requests.get(url, headers=headers)
for item in get_one_page(response.text):
write_to_file(item)
# 将内容写入文件中
def write_to_file(content):
with open('result.txt', 'a', encoding='utf-8') as f:
# 将对象转为 json 字符串
print(type(json.dumps(content)))
f.write(json.dumps(content, ensure_ascii=False) + '\n')
main()
Python 爬取猫眼电影第一页信息
最新推荐文章于 2022-01-01 12:18:34 发布