import json
import requests
from bs4 import BeautifulSoup
from requests.exceptions import RequestException
def get_one_page(url):
try:
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
return None
except RequestException:
return None
def parse_one_page(html):
soup = BeautifulSoup(html, 'lxml')
title_images = soup.select('dd .image-link .board-img')
actors = soup.select('dd div div div .star')
times = soup.select('dd div div div .releasetime')
scores = soup.select('dd div div div .score')
for t_i, actor, time in zip(title_images, actors, times):
yield{
'title':t_i['alt'],
'image':t_i['data-src'],
'actor':actor.get_text().strip()[3:],
'time':time.get_text().strip()[5:]
}
def write_to_file(content):
with open('BS_Maoyan_Top100.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)
for item in parse_one_page(html):
print(item)
write_to_file(item)
if __name__ == '__main__':
for i in range(10):
main(i*10)
网友评论