当前位置: 首页 > news >正文

Python爬虫项目集:豆瓣电影排行榜top250

关于整理日常练习的一些爬虫小练习,可用作学习使用。

爬取项目以学习为主,尽可能使用更多的模块进行练习,而不是最优解。

爬虫概要

示例python 库
爬取模块request
解析模块BeautifulSoup
存储类型list(方便存入数据库)

解析

 

代码示例

# -*- coding: utf-8 -*-import requests
from requests.exceptions import ReadTimeout, ConnectionError, RequestException
from bs4 import BeautifulSoup# 爬虫主体
def get_page(url):headers = {'Connection': 'keep-alive','Cache-Control': 'max-age=0','User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36','Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3','Referer': 'https://maoyan.com/board',}try:response = requests.get(url=url, headers=headers).textreturn responseexcept ReadTimeout:  # 访问超时的错误print('Timeout')except ConnectionError:  # 网络中断连接错误print('Connect error')except RequestException:  # 父类错误print('Error')# 解析网页
def parse_page(html):soup = BeautifulSoup(html, 'lxml')grid = soup.find(name="ol", attrs={"class": "grid_view"})movie_list = grid.find_all("li")for movie in movie_list:rank = movie.find(name="em").getText()name = movie.find(name="span", attrs={"class": "title"}).getText()rating_num = movie.find(name="span", attrs={"class": "rating_num"}).getText()# bd = movie.find(name="p").getText().strip().replace('   ', '\n').replace('...\n                            ', '...\n').replace(' / ', '\n').split('\n')  # 头皮发麻字符串分解系列,因为练习没用 re,果然原生字符串处理麻烦的一匹,strip去除空格,replace替换,旨在将不同信息分类存储到不同的参数,如导演、主演、上映时间、上映时间和电影类型bd = movie.find(name="p").getText().strip().replace('   ', '\n').replace('...\n                            ', '...\n').replace(' / ', '\n').split('\n')  # 头皮发麻字符串分解系列,因为练习没用 re,果然原生字符串处理麻烦的一匹,strip去除空格,replace替换,旨在将不同信息分类存储到不同的参数,如导演、主演、上映时间、上映时间和电影类型# 豆瓣有些主演没有。。。贼蛋疼,为了简便只能写个烂代码再增加一次了if len(bd) == 4:bd.insert(1, '没爬到')inq = movie.find(name="span", attrs={"class": "inq"})# 处理 inq 为空的情况if not inq:inq = "暂无"else:inq = inq.getText()# 这里直接存储到字典,方便存到数据库douBanDict['rank'] = rankdouBanDict['name'] = namedouBanDict['director'] = bd[0]douBanDict['actor'] = bd[1]douBanDict['release_time'] = bd[2].strip()  # 某些列表有空格,直接strip()去除空格douBanDict['country'] = bd[3]douBanDict['movie_types'] = bd[4]douBanDict['rating_num'] = rating_numdouBanDict['inq'] = inqdouBanList.append(str(douBanDict))  # 字典先转为字符串再累加到列表中,否则无法字典值会一直变return douBanListif __name__ == '__main__':douBanList = []douBanDict = {}for start in range(0, 250, 25):url = 'https://movie.douban.com/top250?start={}&filter='.format(start)html = get_page(url)douBanList = parse_page(html)print(douBanList)

数据存储

直接是列表格式,同时包含各个电影信息的字典。

 

http://www.lryc.cn/news/382539.html

相关文章:

  • 34-Openwrt uhttpd与rpcd
  • uni app 树状结构数据展示
  • KVM在线yum源部署-centos 7
  • TSF的服务发现与Consul有何区别?
  • kotlin集合框架
  • 服务器(Linux系统的使用)——自学习梳理
  • 竞赛选题 python+opencv+深度学习实现二维码识别
  • Java读取指定 JAR 包路径中的 git.properties 文件
  • 逻辑回归(Logistic Regression)及其在机器学习中的应用
  • 【计算机视觉】人脸算法之图像处理基础知识【七】
  • 家政预约小程序14权限配置
  • 解决 vue 项目一直出现 sockjs-node/info?t=问题
  • 麒麟信安系统关闭core文件操作
  • 微信小程序轮播图
  • redisson WRONGPASS invalid username-password pair or user is disable
  • QT拖放事件之一:初识拖放4大事件处理函数
  • 使用Python进行数据可视化:从基础到高级
  • 【十二】图解 Spring 核心数据结构:BeanDefinition
  • 速盾:阿里云ddos黑洞是怎么回事?
  • File文件转Blob文件,临时路径浏览器可查看
  • 区块链行业DDOS防护痛点在哪
  • 浏览器自带的IndexDB的简单使用示例--小型学生管理系统
  • 2024年计算机专业还值得选吗?
  • JSON.parse(JSON.stringify())导致的响应式属性丢失
  • SpringBoot引入外部依赖包
  • Spring事务介绍、Spring集成MyBatis
  • 使用GPG来解密和加密文件详解
  • 【Flutter】基础教程:从安装到发布
  • 51单片机学习记录———定时器
  • C# 热插拔---插件开发