import json
from multiprocessing import Pool
import requests
import re
from requests.exceptions import RequestException
# 定义一个函数获取网页的内容
def get_one_page(url):
try:
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
# 尽量加上header:进入网页后右键检查,选择network,Ctrl+R后随便选一个文件即可获得header
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
# 判断是否正常获得网页内容
return None
except RequestsException:
return None
# 定义一个函数获取我们想要的内容的文件,使用正则表达式
def parse_one_page(html):
pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?movie-item-info.*?title="(.*?)".*?'
+ 'star">(.*?)</p>.*?releasetime">(.*?)</p>.*?score-num.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>',
re.S)
items = re.findall(pattern, html)
for item in items:
yield {
'index': item[0],
'image': item[1],
'title': item[2],
'actor': item[3].strip()[3:],
'time': item[4].strip()[5:],
'score': item[5] + item[6]
}
# 定义一个函数将文件写出
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(offset):
url = 'https://maoyan.com/board/4?offset=' + str(offset)
html = get_one_page(url)
parse_one_page(html)
for item in parse_one_page(html):
write_to_file(item)
if __name__ == '__main__':
pool = Pool()
pool.map(main, [i * 10 for i in range(10)])
网友评论