Python 豆瓣TOP250 电影爬取

12 篇文章 1 订阅
1 篇文章 0 订阅


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篇

最近抽空简单学点爬虫。

个人水平有限,有问题欢迎各位大神批评指正!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值