预期效果
代码实现
import requests
from requests.exceptions import RequestException
import re
import json
def get_one_page(url):
try:
response = requests.get(url,
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:57.0) Gecko/20100101 Firefox/57.0'}
)
if response.status_code == 200:
return response.text
return None
except RequestException:
return None
def parse_one_page(html):
pattern = re.compile('<dd>.*?</dd>', re.S)
results = re.findall(pattern, html)
for result in results:
sub_pattern = re.compile(
'<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>',
re.S)
sub_results = re.findall(sub_pattern, result)
for sub_result in sub_results:
yield {
'index': sub_result[0],
'image': sub_result[1],
'title': sub_result[2],
'actor': sub_result[3].strip()[3:],
'time': sub_result[4].strip()[5:],
'score': sub_result[5] + sub_result[6]
}
def write_to_file(content):
with open('maoyan_result.txt', 'a', encoding='utf-8') as f:
f.write(json.dumps(content, ensure_ascii=False) + '\n')
f.close()
def main(offset):
url = 'http://maoyan.com/board/4?offset='+ str(offset)
html = get_one_page(url)
for sub_result in parse_one_page(html):
print(sub_result)
write_to_file(sub_result)
if __name__ == '__main__':
for i in range(10):
main(i*10)
来源:CSDN
作者:FLYING TARDIS
链接:https://blog.csdn.net/weixin_43636302/article/details/103595240