import requests,random,openpyxl,csv
from bs4 import BeautifulSoup
csv_file=open('C:\\Users\\ke\\Desktop\\电影排名250.csv', 'w', newline='')
#调用open()函数打开csv文件,传入参数:文件名“movieTop250.csv”、写入模式“w”、 newline=''。
writer = csv.writer(csv_file)
# 用csv.writer()函数创建一个writer对象。
writer.writerow(['序号', '电影名', '评分', '推荐语', '链接'])
headers = {
'Host': 'movie.douban.com',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Edg/92.0.902.84',
}
for x in range(10):
url = 'https://movie.douban.com/top250?start=' + str(x*25) + '&filter='
res = requests.get(url,headers=headers,allow_redirects=False)
res.encoding = res.apparent_encoding
bs = res.text
soup = BeautifulSoup(bs,'html.parser')
movies = soup.find('ol', class_="grid_view").find_all('li')
for titles in movies:
num = titles.find('em',class_="").text
title = titles.find('span', class_="title").text
comment = titles.find('span',class_="rating_num").text
url_movie = titles.find('div',class_ = 'hd').find_next('a')['href']
if titles.find('span',class_="inq") != None:
tes = titles.find('span',class_="inq").text
writer.writerow([num + '.' + title + '——' + comment + '\n' + '推荐语:' + tes +'\n' + url_movie])
else:
writer.writerow([num + '.' + title + '——' + comment + '\n' +'\n' + url_movie])
csv_file.close()
问题出现在第19行的find_all
这个问题你已经问过了吧?
你从一个远端设备获取信息,每一步都应该做非空判断,不要写连续的点
我推断你的soup.find('ol', class_="grid_view")返回值是None,仔细检查它为什么是None,而不是纠结None.find_all为什么会报错