博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python0基础爬取豆瓣电影Top250,CV可运行
阅读量:3961 次
发布时间:2019-05-24

本文共 8790 字,大约阅读时间需要 29 分钟。

目录

1.装好python环境

2.步骤

2.1 爬取网页

2.2 逐一解析数据
2.3保存数据

3.导包:

from bs4 import BeautifulSoup #网页解析,获取数据import re #正则表达式,进行文字匹配import urllib.request,urllib.error #指定URL,获取网页数据import xlwt #进行excel操作import _sqlite3 #进行sqllite操作

4.完整代码

# -*- coding: utf-8 -*-from bs4 import BeautifulSoup #网页解析,获取数据import re #正则表达式,进行文字匹配import urllib.request,urllib.error #指定URL,获取网页数据import xlwt #进行excel操作import _sqlite3 #进行sqllite操作def main():    baseurl="https://movie.douban.com/top250?start="    # 1.爬取网页    dataList=getDate(baseurl)    savePath="豆瓣电影Top250.xls"    # 3.保存数据    saveDate(dataList,savePath)    #askURL("https://movie.douban.com/top250?start=")#影片详情连接的规则  #findLink =re.compile(r'')  #创建正则表达式对象,表示规则(字符串模式)  r  忽略转义字符#获取图片  #肖申克的救赎findImgSrc=re.compile(r'
肖申克的救赎findTitle=re.compile(r'
(.*)')#影片评分
9.7findRating=re.compile(r'
(.*)')#找到评价人数 #爬取网页
2149182人评价findJudge=re.compile(r'
(\d*)人评价')#找到概括
希望让人自由。findInq=re.compile(r'
(.*)')#找到影片的相关内容findBd=re.compile(r'

(.*?)

',re.S)def getDate(baseurl): dataList=[] for i in range(0,10): #调用获取页面信息的函数,10次 url=baseurl+str(i*25) html=askURL(url) #保存获取到的网页源码 # 2.逐一解析数据 soup=BeautifulSoup(html,"html.parser") for item in soup.find_all('div',class_="item"): #查找符合要求的字符串,形成列表 #print(item) #测试查看电影item的全部信息 data=[] #保存一部电影的所有信息 item=str(item) #将item转为字符串 titles = re.findall(findTitle, item) # 片名可能只有一个,没有外国名 if (len(titles) == 2): ctitle = titles[0] # 添加中文名 data.append(ctitle) otitle = titles[1].replace("/", "") # 去掉无关字符 data.append(otitle) # 添加外国名 else: data.append(titles[0]) data.append(' ') # 外国名留空 link=re.findall(findLink,item)[0] #re库用来通过正则表达式查找指定的字符串 data.append(link) #添加链接 imgSrc=re.findall(findImgSrc,item)[0] data.append(imgSrc) #添加图片 rating=re.findall(findRating,item)[0] data.append(rating) #添加评分 judgeNum=re.findall(findJudge,item)[0] data.append(judgeNum) #增加评分人数 inq=re.findall(findInq,item) if len(inq)!=0: inq=inq[0].replace("。","") #去掉句号 data.append(inq) #添加概况 else: data.append(" ") #没有概述留空 bd=re.findall(findBd,item)[0] #相关信息 bd=re.sub('
(\s+)?'," ",bd) #去掉
bd=re.sub('/'," ",bd) #替换/ data.append(bd.strip()) #去掉前后的空格 dataList.append(data) #把处理好的一部电影信息放入dataList #print(dataList) print(len(dataList)) return dataList#得到指定一个url的网页内容def askURL(url): head ={
#模拟浏览器头部信息,向豆瓣服务器发送消息 "User-Agent": #换成自己的信息 } #用户代理,表示告诉豆瓣服务器,我们是什么类型的机器,浏览器(本质上是告诉浏览器,我们可以接受什么水平的文件内容) request=urllib.request.Request(url,headers=head) html=" " try: response=urllib.request.urlopen(request) html=response.read().decode("utf-8") #print(html) except urllib.error.URLError as e: if hasattr(e,"code"): print(e.code) if hasattr(e,"reason"): print(e.reason) return html#保存数据def saveDate(dataList,savePath): print("save...") workbook = xlwt.Workbook(encoding="utf-8",style_compression=0) # 创建workbook对象 worksheet = workbook.add_sheet('豆瓣电影Top250',cell_overwrite_ok=True) # 创建工作表 col=("电影中文名","电影外国名","电影详情链接","图片链接","评分","评分人数","概括","相关信息") for i in range(0,8): worksheet.write(0,i,col[i]) #列名 for i in range(0,250): print("第%d条" %(i+1)) data=dataList[i] for j in range(0,8): worksheet.write(i+1,j,data[j]) #数据 workbook.save(savePath) # 保存数据表if __name__ == '__main__': main() print("爬取完毕!!!!!!")

5. 效果

在这里插入图片描述

6.补充知识

6.1 urllib相关

# -*- coding: utf-8 -*-import urllib.request# #获取一个get请求# response=urllib.request.urlopen("http://www.baidu.com")# print(response.read().decode('utf-8')) #对获取到的的网页源码进行utf-8解码# #获取一个post请求# import urllib.parse# data=bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8")# response=urllib.request.urlopen("http://httpbin.org/post",data=data)# print(response.read().decode('utf-8'))#超时处理# try:#     response=urllib.request.urlopen("http://httpbin.org/get",timeout=0.01)#     print(response.read().decode('utf-8'))# except urllib.error.URLError as e:#     print("time out!")# response=urllib.request.urlopen("http://www.baidu.com")# print(response.status)# #urllib.error.HTTPError: HTTP Error 418:   418发现你是爬虫# #print(response.getheaders())#看全部# print(response.getheader("Server"))#看某个值#模拟浏览器访问# #url="https://www.douban.com/"# url="http://httpbin.org/post"# headers={
# "User-Agent": #自己的信息# }# data=bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8")#post请求需要模拟参数# req=urllib.request.Request(url=url,data=data,headers=headers,method="POST")# response=urllib.request.urlopen(req)# print(response.read().decode("utf-8"))url="https://www.douban.com/"headers={
"User-Agent": #自己的信息}req=urllib.request.Request(url=url,headers=headers)response=urllib.request.urlopen(req)print(response.read().decode("utf-8"))

6.2 Re

# -*- coding: utf-8 -*-#正则表达式:字符串模式(判断字符串是否符合一定的标准)import re# #创建模式对象# pat=re.compile("AA") #此处的AA,是正则表达式,用来去验证其他的字符串# m=pat.search("CBAADDAA") #search字符串:被校验的内容#没有模式对象# m=re.search("asd","Aasd") #前面的字符串时规则(模板),后面的字符串是被校验的对象# print(m)#print(re.findall("a","ASfaafFAF")) #['a', 'a']#print(re.findall("[A-Z]","ASfaafFAF")) #['A', 'S', 'F', 'A', 'F']#print(re.findall("[A-Z]+","ASfaafFAF")) #['AS', 'FAF']#print(re.sub("a","A","abcda")) #AbcdA#建议在正则表达式中,被比较的字符串前面加上r,不用担心转义字符的问题a=r"\aabc\'"print(a)  #\aabc\'

6.3 Bs4

# -*- coding: utf-8 -*-'''bs4是什麽?它的作用是能够快速方便简单的提取网页中指定的内容,给我一个网页字符串,然后使用它的接口将网页字符串生成一个对象,然后通过这个对象的方法来提取数据-Tag-NavigableString-BeautifulSoup-Comment'''from bs4 import BeautifulSoupfile =open("b.html","rb")html=file.read().decode("utf-8")bs=BeautifulSoup(html,"html.parser")#print(bs.title) #百度一下,你就知道#print(bs.a)#print(bs.head)#print(type(bs.head)) #
#1.Tag 标签及其内容:拿到他所找到的第一个内容# print(bs.title.string)#百度一下,你就知道# print(type(bs.title.string))#
#2.NavigableString 标签里的内容(字符串)#print(bs.a.attrs) #{'href': 'http://news.baidu.com', 'target': '_blank', 'class': ['mnav', 'c-font-normal', 'c-color-t']}#拿到标签及其所有属性# print(type(bs))#
# #3.BeautifulSoup 表示整个文档# print(bs.name)#[document]# print(bs)# print(bs.a.string)#新闻# print(type(bs.a.string))#
#4.Comment 是一个特殊的NavigableString,输出内容不包含注释符号#------------------应用----------------------#文档的遍历#print(bs.head.contents)#print(bs.head.contents[1])#搜索BeautifulSoup文档,查看更多#文档的搜索#(1)find_all***********************************************#t_list =bs.find_all("a")import re#正则表达式搜索:使用search()方法来匹配内容#t_list=bs.find_all(re.compile("a"))#方法:传入一个函数(方法),根据函数的要求来搜索(了解)# def name_is_exists(tag):# return tag.has_attr("name")# t_list=bs=bs.find_all(name_is_exists)## for item in t_list:# print(item)# #print(t_list)#(2)Kwargs 参数***********************************************# t_list=bs.find_all(id="head")## t_list=bs.find_all(class_=True)## t_list=bs.find_all(href="http://news.baidu.com")# for item in t_list:# print(item)#(3)text 参数***********************************************# t_list=bs.find_all(text="hao123")# t_list=bs.find_all(text=["hao123","地图"])# t_list=bs.find_all(text=re.compile("\d")) #应用正则表达式来查找包含特定文本的内容(标签里的字符串)# for item in t_list:# print(item)#(4)limit 参数***********************************************# t_list=bs.find_all("a",limit=3)# for item in t_list:# print(item)#(5)css选择器***********************************************# t_list=bs.select('title') #通过标签来查找# t_list=bs.select('.mnav') #通过类名来查找# t_list=bs.select('#u1') #通过类名来查找#t_list=bs.select("a[class='mnav c-font-normal c-color-t']") #通过属性来查找#t_list=bs.select("head > title")#通过子标签查找t_list=bs.select(".mnav ~ .aaa")#通过兄弟查找print(t_list[0].get_text())# for item in t_list:# print(item)

6.4 Xwlt

# -*- coding: utf-8 -*-import xlwt'''workbook=xlwt.Workbook(encoding="utf-8")        #创建workbook对象worksheet=workbook.add_sheet('sheet1')          #创建工作表worksheet.write(0,0,"hello")                    #写入数据,第一个参数”行“,第二个参数”列“,第三个参数”内容“workbook.save("student.xls")                    #保存数据表'''workbook=xlwt.Workbook(encoding="utf-8")        #创建workbook对象worksheet=workbook.add_sheet('sheet1')          #创建工作表for i in range(0,9):    for j in range(0,i+1):        worksheet.write(i,j,"%d * %d = %d"%(i+1,j+1,(i+1)*(j+1)))workbook.save("student.xls")                    #保存数据表

转载地址:http://xcezi.baihongyu.com/

你可能感兴趣的文章
log4cxx 的编译安装过程和使用
查看>>
简单邮件系统程序
查看>>
STL里的multimap使用详解
查看>>
STL 库其中的 std::string用法总结
查看>>
模态对话框的销毁过程与非模态对话的几种销毁方法
查看>>
C++实现http下载 && 24点计算编码风格
查看>>
memcached了解使用和常用命令详解
查看>>
GDB调试各功能总结
查看>>
"undefined reference to" 多种可能出现的问题解决方法
查看>>
类结构定义
查看>>
Windows下关于多线程类 CSemaphore,CMutex,CCriticalSection,CEvent,信号量CSemaphore的使用介绍
查看>>
图像处理基本算法(汇总)以及实现
查看>>
C++编程获取本机网卡信息 本机IP 包括Windows和Linux
查看>>
C++连接CTP接口实现简单量化交易
查看>>
服务端使用c++实现websocket协议解析及通信
查看>>
C# string.Format使用说明
查看>>
Linux下安装Mysql数据库开发环境
查看>>
Linux用户及用户组添加和删除操作
查看>>
通用 Makefile 的编写方法以及多目录 makefile 写法
查看>>
C++的4种智能指针剖析使用
查看>>