源码⼤公开!Python爬取⾖瓣电影Top250源代码,赶紧收
藏!
哈喽~⼤家好,我是恰恰。不知道是不是有很多⼩伙伴跟我⼀样,很喜欢看电影,尤其是那种别⼈推荐的⾖瓣⾼分电影,所以学Python就有⼀个好处,⽤Python爬取⾖瓣电影那是分分钟的事,再也不⽤因为有些电影看不了⽽难受了。  所以看到这⾥了赶紧给我点赞收藏起来~码住在学!
这篇内容使⽤Python爬取⾖瓣电影Top250,含完整源代码,并实现两种⽅式保存数据(excel和数据库)主要分为四步:1、获取页⾯源代码;2、获取标签;3、正则表达式匹配;4、保存数据。先上完整代码,后⾯再对重点部分进⾏解析。
程序运⾏截图:
from bs4 import BeautifulSoup #页⾯解析,获取数据
import re #正则表达式
#指定URL,获取页⾯数据
import xlwt #进⾏excel操作
import sqlite3 #进⾏sql操作
def main():
baseUrl = "movie.douban/top250?start="
#1.爬取⽹页,并解析数据
dataList = getData(baseUrl)
savePath=".\\⾖瓣电影Top250.xls"
#savePath = "movies.db"
#2.保存数据
saveData(dataList,savePath)
#savedb(dataList,savePath)
#---正则表达式---
#链接
findLink = repile(r'<a href="(.*?)">',re.S)
#电影名字
findName = repile(r'<span class="title">(.*?)</span>',re.S)
#评分
findRating = repile(r'<span class="rating_num" property="v:average">(.*?)</span>') #标题
findInq = repile(r'<span class="inq">(.*?)</span>',re.S)
#评分⼈数
findCount = repile(r'<span>(.*?)⼈评价</span>')
#电影信息
findInf = repile(r'<p class="">(.*?)</p>',re.S)
#1.爬取⽹页
def getData(baseUrl):
dataList = []
for i in range(10):
html = askUrl(baseUrl + str(i * 25))
# 2.逐⼀解析数据
bs = BeautifulSoup(html,"html.parser")
for item in bs.find_all('div',class_="item"):
data = []
item = str(item)
#链接
link = re.findall(findLink,item)[0]
#名字
name = re.findall(findName,item)
if len(name) == 1:
cName = name[0]
fName = " "
else:
name[1] = name[1].replace(" / ","")
cName = name[0]
fName = name[1]
#评分
rating = re.findall(findRating,item)[0]
#标题
inq = re.findall(findInq,item)
if len(inq) < 1:
inq = " "
else:
inq= inq[0]
#评分⼈数
racount = re.findall(findCount,item)[0]
#电影信息
inf = re.findall(findInf,item)[0]
inf = re.sub("...<br(\s+)?/>(\s?)"," ",inf)
inf = re.sub("/"," ",inf)
inf  = inf.strip()
#添加⼀部电影的信息进data
data.append(link)
data.append(cName)
data.append(fName)
data.append(rating)
data.append(inq)
data.append(racount)
data.append(inf)
dataList.append(data)
return dataList
#爬取指定url
def askUrl(url):
head = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.7    request = quest.Request(url = url,headers=head)
http = ""
try:
response = quest.urlopen(request)
http = ad().decode("utf-8")
URLError as e:
if hasattr(e,"code"):
de)
if hasattr(e,"reson"):
son)
return http
电影源代码人物介绍# 3.保存数据
def saveData(dataList,savePath):
woke = xlwt.Workbook("utf-8",style_compression=0)#样式的压缩效果
sheet = woke.add_sheet("⾖瓣电影Top250",cell_overwrite_ok=True)#覆盖原单元格信息
col = ("链接","中⽂名字","英⽂名字","评分","标题","评分⼈数","概况")
for i in range (7):
sheet.write(0,i,col[i])
sheet.write(0,i,col[i])
for i in range (0,250):
for j in range (7):
sheet.write(i+1,j,dataList[i][j])
print("第%d条数据"%(i+1))
woke.save(savePath)
print("保存完毕")
#3.保存到数据库
def savedb(dataList,dataPath):
initdb(dataPath)
conn = t(dataPath)
cur = conn.cursor()
#开始保存数据
for data in dataList:
for index in range(len(data)):
data[index] = str('"'+data[index]+'"')
newstr = ",".join(data)
sql ="insert into movie(info_link,cname,fname,rating,inq,racount,inf)values(%s)"%(newstr)        print(sql)
connmit()
cur.close()
conn.close()
print("保存完毕")
#3-1新建表
def initdb(dataPath):
conn = t(dataPath)
cur = conn.cursor()
sql = '''
create table movie(
id Integer primary key autoincrement,
info_link text,
cname varchar ,
fname varchar ,
rating varchar ,
inq text,
racount varchar ,
inf text
)
'''
connmit()
cur.close()
conn.close()
if __name__ == "__main__":
#调⽤函数
main()
⼀、获取页⾯源代码
1. 伪装成浏览器;
2.进⼀步包装请求;
3.⽹页请求获取数据;
4.解析并保存;
5.返回数据。
#指定URL,获取页⾯数据
#爬取指定url
def askUrl(url):
#请求头伪装成浏览器(字典)
head = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.7    #进⼀步包装请求
request = quest.Request(url = url,headers=head)
#存储页⾯源代码
html = ""
try:
#页⾯请求,获取内容
response = quest.urlopen(request)
#读取返回的内容,⽤"utf-8"编码解析
html = ad().decode("utf-8")
URLError as e:
if hasattr(e,"code"):
de)
if hasattr(e,"reson"):
son)
#返回页⾯源代码
return html
⼆、获取标签
通过BeautifulSoup进⼀步解析页⾯源代码

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。