文章目录
0 问题需求
豆瓣TOP250电影的序号/电影名/评分/推荐语/链接的爬取
1 遇到的问题
1.1 AttributeError: ‘NoneType’ object has no attribute ‘find_all’
res = requests.get(url)
print(res.status_code)
状态码为418,非200
设置headers信息可以解决,解决步骤如下:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'}
res = requests.get(url, headers=headers)
print(res.status_code)
详细说明见AttributeError: ‘NoneType’ object has no attribute ‘find_all’(添加请求头信息).
1.2 AttributeError: ‘NoneType’ object has no attribute ‘text’
151.喜宴——8.9
推荐语:中国家庭的喜怒哀乐忍。
https://movie.douban.com/subject/1303037/
后报错,查看后发现为:
编号152没有推荐语,而空值是没办法做text⽂本转换的,因此报错
需要对推荐语是否为空做相应判断
2 代码
import requests
import bs4
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'}
for x in range(10):
url = 'https://movie.douban.com/top250?start=' + str(x*25) + '&filter='
res = requests.get(url, headers=headers)
# print(res.status_code)
bs = bs4.BeautifulSoup(res.text, 'html.parser')
bs = bs.find('ol', class_="grid_view")
for titles in bs.find_all('li'):
# 查找序号
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('a')['href']
# 查找推荐语
if titles.find('span', class_="inq") is not None:
tes = titles.find('span',class_="inq").text
print(num + '.' + title + '——' + comment + '\n' + '推荐语:' + tes + '\n' + url_movie)
else:
print(num + '.' + title + '——' + comment + '\n' + url_movie)
3 结语
第49篇
最近抽空简单学点爬虫。
个人水平有限,有问题欢迎各位大神批评指正!