python爬取豆瓣电影top250并保存为xlsx_python 爬虫获取豆瓣电影排行榜前250并写入excel...
豆瓣电影排行榜前250 分为10页,第一页的url为https://movie.douban.com/top250,但实际上应该是https://movie.douban.com/top250?start=0 后面的参数0表示从第几个开始,如0表示从第一(肖申克的救赎)到第二十五(触不可及),https://movie.douban.com/top250?start=25表示从第二十六(蝙蝠侠:黑暗骑士)到第五十名(死亡诗社)。等等,
所以可以用一个步长为25的range的for循环参数
for i in range(0, 250, 25):print(i)
分析完页面组成后,开始获取页面,直接request.get()发现没有返回任何东西,输出一下响应码
url = 'https://movie.douban.com/top250?start=0'res= request.get(url=url)print(res.status_code)
发现返回响应码418
以前没见过这个,拉网线上网查一下,发现给get里面加一个header参数就行了
这里可以用自己浏览器的user-agent,如
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}
或者用fake_agent(安装直接用pip install fake_agent) 来为自己生成一个随机的agent添加到header字典中
from fake_useragent importUserAgent
headers= {'User-Agent': UserAgent().random}
之后就可以得到页面源码了。
然后使用lxml.etree,即xpath解析页面源码。用浏览器插件xpath finder快速定位到元素
importrequestsimportlxml.etree as etree
url= 'https://movie.douban.com/top250?start=0'headers= {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}
res= requests.get(url=url, headers=headers)print(res.text)
html=etree.HTML(res.text)
name= html.xpath("/html/body/div[3]/div[1]/div/div[1]/ol/li[1]/div/div[2]/div[1]/a/span[1]")print(name)
但是直接这样子,解析到的是这样的结果
[]
这里我直接写解决部分,在使用xpath解析时,后面加上/text()
name = html.xpath("/html/body/div[3]/div[1]/div/div[1]/ol/li[1]/div/div[2]/div[1]/a/span[1]/text()")
解决后,再使用xpath finder插件,一步一步获取到电影所有数据
最后把这个写在函数里,外面再套上一开始说的循环,就OK了
# -*- coding: utf-8 -*-
import requests
import lxml.etree as etree
def get_source(page):
url = 'https://movie.douban.com/top250?start={}'.format(page)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}
print(url)
res = requests.get(url=url, headers=headers)
print(res.status_code)
html = etree.HTML(res.text)
for i in range(1, 26):
name = html.xpath("/html/body/div[3]/div[1]/div/div[1]/ol/li[{}]/div/div[2]/div[1]/a/span[1]/text()".format(i))
info = html.xpath("/html/body/div[3]/div[1]/div/div[1]/ol/li[{}]/div/div[2]/div[2]/p[1]/text()".format(i))
score = html.xpath(
"/html/body/div[3]/div[1]/div/div[1]/ol/li[{}]/div/div[2]/div[2]/div/span[2]/text()".format(i))
slogan = html.xpath(
"/html/body/div[3]/div[1]/div/div[1]/ol/li[{}]/div/div[2]/div[2]/p[2]/span/text()".format(i))
print(name[0])
print(info[0].replace(' ', ''))
print(info[1].replace(' ', ''))
print(score[0])
print(slogan[0])
n = 1
for i in range(0, 250, 25):
print('第%d页' % n)
n += 1
get_source(i)
print('==========================================')
在定位时,发现有4部电影介绍没有slogan,导致获取到的信息为空列表,也就导致了list.append()会出错。所以我加上了几个差错处理,解决方式可能有点傻,如果有更好的解决办法,洗耳恭听
代码在最后可以看到
EXCEL保存部分
这里我用的xlwt
book =xlwt.Workbook()
sheet= book.add_sheet(u'sheetname', cell_overwrite_ok=True)
创建一个sheet表单。
数据保存到一个大列表中,列表嵌套列表
再通过循环把数据导入到excel表单中
r = 1
for i in LIST: #有10页
for j in i: #有25条数据
c = 2
for x in j: #有5组数据
print(x)
sheet.write(r, c, x)
c+= 1r+= 1
最后在保存一下
book.save(r'douban.xls')
注意文件后缀要用xls,用xlsx会导致文件打不开
然后就大功告成了
打开文件,手动加入排名,等部分信息(这些也可以在程序里完成,我嫌麻烦,就没写,直接手动来的快)
前面的✓是我自己整的,用于记录那些看过,那些没看过
这也是我写这个东西的最初的目的
完整代码在下面,仅用于参考
#-*- coding: utf-8 -*-
importrequestsimportlxml.etree as etreeimportxlwtdefget_source(page):
List=[]
url= 'https://movie.douban.com/top250?start={}'.format(page)
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}print(url)
res= requests.get(url=url, headers=headers)print(res.status_code)
html=etree.HTML(res.text)for i in range(1, 26):
list=[]
name= html.xpath("/html/body/div[3]/div[1]/div/div[1]/ol/li[{}]/div/div[2]/div[1]/a/span[1]/text()".format(i))
info= html.xpath("/html/body/div[3]/div[1]/div/div[1]/ol/li[{}]/div/div[2]/div[2]/p[1]/text()".format(i))
score=html.xpath("/html/body/div[3]/div[1]/div/div[1]/ol/li[{}]/div/div[2]/div[2]/div/span[2]/text()".format(i))
slogan=html.xpath("/html/body/div[3]/div[1]/div/div[1]/ol/li[{}]/div/div[2]/div[2]/p[2]/span/text()".format(i))try:
list.append(name[0])except:
list.append('----')try:
list.append(info[0].replace(' ', '').replace('\n', ''))except:
list.append('----')try:
list.append(info[1].replace(' ', '').replace('\n', ''))except:
list.append('----')try:
list.append(score[0])except:
list.append('----')try:
list.append(slogan[0])except:
list.append('----')
List.append(list)returnList
n= 1LIST=[]for i in range(0, 250, 25):print('第{}页'.format(n))
n+= 1List=get_source(i)
LIST.append(List)defexcel_write(LIST):
book=xlwt.Workbook()
sheet= book.add_sheet(u'sheetname', cell_overwrite_ok=True)
r= 1
for i in LIST: #有10页
for j in i: #有25条数据
c = 2
for x in j: #有5组数据
print(x)
sheet.write(r, c, x)
c+= 1r+= 1book.save(r'douban1.xls') #保存代码
excel_write(LIST)
python爬取豆瓣电影top250并保存为xlsx_python 爬虫获取豆瓣电影排行榜前250并写入excel...相关推荐
- python爬取豆瓣电影top250并保存为xlsx_Python 爬虫 存储Excel - 豆瓣电影Top250
from bs4 import BeautifulSoup #网页解析,获取数据 import re #正则表达式,进行文字匹配 import urllib.request,urllib.error ...
- 使用python爬取喜马拉雅音频数据并保存
** 使用python爬取喜马拉雅音频数据并保存 ** 1.进入喜马拉雅官网,打开要爬取的项目网页,按F12=>F5后进行清空,点击项目网页中播放按钮,出现如下图点击,查找网页的url,获取到网 ...
- python爬取网站图片链接并保存,Python爬取网站图片并保存的实现示例
先看看结果吧,去bilibili上拿到的图片=-= 第一步,导入模块 import requests from bs4 import BeautifulSoup requests用来请求html页面, ...
- Python爬取网易云音乐热歌榜(爬虫)
Python爬取网易云音乐热歌榜歌曲,并下载到本地 找到要下载歌曲排行榜的链接,这里用的是: https://music.163.com/discover/toplist?id=3778678 然后更 ...
- Python爬取链家成都二手房源信息,异步爬虫实战项目!
本文先熟悉并发与并行.阻塞与非阻塞.同步与异步.多线程.多线程.协程的基本概念.再实现asyncio + aiohttp爬取链家成都二手房源信息的异步爬虫,爬取效率与多线程版进行简单测试和比较. 1. ...
- python爬取微博热搜并存入表格_python爬虫进阶之爬取微博热搜存入Mysql
在编程中,我们如果想要把数据转入数据库中,首先会选择 MySQL数据库.因为MySQL数据库体积小.速度快.总体拥有成本低.开放源代码,其有着广泛的应用,例如我们使用python爬虫微博热搜,就可以使 ...
- python爬取小说写入txt_燎原博客—python爬取网络小说存储为TXT的网页爬虫源代码实例...
python是一门优秀的计算机编程语言,两年前曾因为动过自动化交易的念头而关注过它.前几天在微信上点了个python教学的广告,听了两堂课,所以现在又热心了起来,照葫芦画瓢写了一段简单的网络爬虫代码, ...
- python 爬取自如租房的租房数据,使用图像识别获取价格信息
python 爬取自如租房的租房数据 完整代码下载:https://github.com/tanjunchen/SpiderProject/tree/master/ziru #!/usr/bin/py ...
- python爬取豆瓣电影top250并保存为xlsx_python抓取豆瓣电影Top250数据并写入Excel
douban python抓取豆瓣电影Top250数据并写入Excel 1.将目标网站上的页面抓取下来 2.将抓取下来的数据根据一定的规则进行提取 create table `tb_movie`( i ...
最新文章
- Deepin系统安装
- 解决Maven工程install时[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources
- 第一个Appium脚本
- java resttemplate_java-通过resttemplate通过Spring Rest服务发送文...
- 深入理解JSON对象
- php load dynamic library,PHP startup: Unable to load dynamic library错误的错误
- 记一次ElasticSearch重启之后shard未分配问题的解决
- matplotlib 添加偏移量
- 【网摘】 浅谈HTTP中GET与POST的区别
- Python——装饰器的学习笔记(legacy)
- 让线程按顺序执行8种方法
- html静态网页制作天天生鲜,天天生鲜 前后台资源
- java生成随机数的三种方法
- wincc逻辑运算符_wincc表达式符号
- 世界史上的6大古帝国
- PHP动态网站开发期末试卷,《PHP动态网站开发实例教程》课程考核方案
- Simple Contrastive Representation Adversarial Learning for NLP Tasks
- 任务分配的穷举法、匈牙利法、分支定界法
- 【力扣(LeetCode)】【C/C++】【19.删除链表的倒数第 N 个结点】
- JetBrains历史版本下载