鱼C论坛

 找回密码
 立即注册
查看: 2783|回复: 0

[作品展示] 爬取豆瓣电影排行榜

[复制链接]
发表于 2020-9-7 00:36:10 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. import requests
  2. from bs4 import BeautifulSoup
  3. import time


  4. headers = {
  5.     'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
  6. }


  7. with open('豆瓣电影排行榜.txt', 'w', encoding='utf-8') as file:
  8.     for page in range(10):
  9.         url = 'https://movie.douban.com/top250?start={}&filter='.format(page*25)
  10.         res = requests.get(url, headers=headers)
  11.         soup = BeautifulSoup(res.text, 'html.parser')
  12.         for item in soup.select('div.item'):
  13.             tag = item.select('div.hd a')
  14.             link = tag[0]['href']  # 地址
  15.             name = tag[0].select('span.title')[0].text  # 影片名称
  16.             content = item.select('div.bd p.quote span.inq')  # 简介
  17.             score = item.select('div.bd div.star span.rating_num')[0].text  # 评分
  18.             number_of_score = item.select('div.bd div.star')[0].text.split()[-1]  # 评价人数
  19.             information = item.select('div.bd p')[0].text.split()  # 信息列表
  20.             if [y for y in information if y.isdigit()]:
  21.                 year = [y for y in information if y.isdigit()][0] + '年'  # 上映时间
  22.             else:
  23.                 year = '暂无数据'
  24.             if content:  # 判断是否为None
  25.                 content = content[0].text
  26.             else:
  27.                 content = '此影片尚无简介'

  28.             file.write(f'影片名称:《{name}》\n')
  29.             file.write(f'上映时间:{year}\n')
  30.             file.write(f'影片评分:{number_of_score},得分{score}分\n')
  31.             file.write(f'影片简介:{content}\n')
  32.             file.write(f'影片地址:{link}\n')
  33.             file.write('\n')

  34.         print(f'第{page+1}页爬取完毕')
  35.         time.sleep(2)
  36.     else:
  37.         print('done!')
复制代码

初学爬虫,都在拿TOP250的电影练手,我也来试试
在爬取的过程中有部分页面没有数据(比如年份,简介)可能会导致下标越界等错误,要特殊处理。
尝试用了find_all 以及 css选择器方法(目前只会这两种)。发现CSS选择器好用很多。。
微信截图_20200907003337.png
微信截图_20200907003410.png
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-26 18:37

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表