刚开始学,UA直接网页上复制一个呗import requests
from bs4 import BeautifulSoup
import time
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
}
with open('豆瓣电影排行榜.txt', 'w', encoding='utf-8') as file:
for page in range(10):
url = 'https://movie.douban.com/top250?start={}&filter='.format(page*25)
res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')
for item in soup.select('div.item'):
tag = item.select('div.hd a')
link = tag[0]['href'] # 地址
name = tag[0].select('span.title')[0].text # 影片名称
content = item.select('div.bd p.quote span.inq') # 简介
score = item.select('div.bd div.star span.rating_num')[0].text # 评分
number_of_score = item.select('div.bd div.star')[0].text.split()[-1] # 评价人数
information = item.select('div.bd p')[0].text.split() # 信息列表
if [y for y in information if y.isdigit()]:
year = [y for y in information if y.isdigit()][0] + '年' # 上映时间
else:
year = '暂无数据'
if content: # 判断是否为None
content = content[0].text
else:
content = '此影片尚无简介'
file.write(f'影片名称:《{name}》\n')
file.write(f'上映时间:{year}\n')
file.write(f'影片评分:{number_of_score},得分{score}分\n')
file.write(f'影片简介:{content}\n')
file.write(f'影片地址:{link}\n')
file.write('\n')
print(f'第{page+1}页爬取完毕')
time.sleep(2)
else:
print('done!')
|