笔记根据视频做出爬取豆瓣Top250条记录
后续可通过爬取出来的数据进行数据分析和可视化
首先搭建框架 spider.py
# -*- codeing = utf-8 -*-
import sys
from bs4 import BeautifulSoup # 网页解析,获取数据
import re #正则,进行文字匹配
import urllib.request,urllib.error #制定url,获取网页数据
import xlwt #进行excel操作
import sqlite3
def main():
baseurl = 'https://movie.douban.com/top250?start='
#1.爬取网页
datalist = getData(baseurl)
savepath='豆瓣电影Top250.xls'
#3.保存数据
saveData(datalist,savepath)
#爬取网页
def getData(baseurl):
pass
#得到指定一个URL的网页内容
def askURL(url):
pass
#保存数据
def saveData(datalist,savepath):
pass
if __name__ == '__main__': # 当程序执行时
main()
print("爬取完成")
测试如何爬取到一整个页面html
由于得到指定一个URL的网页内容,所以用testUrllib.py测试获取整个页面html
#测试获取整个页面html
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.de({"hello":"world"})urlenco,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=1)
# response = urllib.request.urlopen("http://httpbin.org/get",timeout=0.01)
# print(response.read().decode('utf-8')) #对获取到的网页源码进行utf-8解码
# except urllib.error.URLError as e:
# print('time out!!!')
# response = urllib.request.urlopen("http://httpbin.org/get")
# # print(response.status) #状态码
# print(response.getheaders())
# print(response.getheader("Server"))
# url="http://httpbin.org/post"
# headers={
# "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"
# }
# data=bytes(urllib.parse.urlencode({'name':'eric'}),encoding='utf-8')
# 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://movie.douban.com/top250"
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"
}
req = urllib.request.Request(url=url,headers=headers)
response = urllib.request.urlopen(req)
print(response.read().decode('utf-8'))
完善spider.py中的askURL方法
#得到指定一个URL的网页内容
def askURL(url):
head={ # 模拟浏览器头部信息 (伪装)
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"
} #用户代理,表示告诉豆瓣服务器,我们是一个浏览器(本质上是告诉浏览器,我们可以接受什么水平的文件内容)
request = urllib.request.Request(url, headers=head)
html=""
try:
response=urllib.request.urlopen(request)
html=response.read().decode('utf-8')
# print(html)
except Exception as e:
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
return html
测试如何解析数据
在获取到html的页面数据后,再解析数据(定位取到你需要的数据),在testBs4中,了解BeautifulSoup4的使用
# 如何解析数据
'''
BeautifulSoup4将复杂html文档转换成一个复杂的树形结构,每个
节点都是python对象,所有对象可以归纳为4中
- Tag
- NavigableString
- BeautifulSoup
- Comment
'''
from bs4 import BeautifulSoup
file = open("xxx.html","rb")
html = file.read().decode('utf-8')
bs = BeautifulSoup(html,"html.parser") # 通过BeautifulSoup指定解析器解析文档
# print(bs.title)
# print(bs.a)
# print(bs.head)
# print(type(bs.head)) #Tag类型
#1.Tag 标签及其内容:拿到它所有找到的第一个
# print(bs.title.string)
# print(type(bs.title.string))
#2.NavigableString 标签里面的内容(字符串)
# print(bs.a.attrs) #一个字典 a标签中键值对返回
# print(type(bs))
#3.BeautifulSoup 表示整个文档
# print(bs)
# print(bs.a.string)
# print(type(bs.a.string))
#4.Comment 是一个特殊的NavigableString,输出的内容不包含注释符号
#-------------------------------------
#文档的遍历
# print(bs.head.contents)
# print(bs.head.contents[1])
#文档的搜索*** 提取有用信息(重点)
# (1)find_all()
#字符串过滤:会查找与字符串完全匹配的内容
# t_list=bs.find_all("a")
#正则表达式搜索:使用search()方法来匹配内容
import re
# t_list = bs.find_all(re.compile("a")) #只要标签里含有a
#方法:传入一个函数(方法),根据函数的要求来搜索(了解)
# def name_is_exists(tag):
# return tag.has_attr("name")
#
# t_list=bs.find_all(name_is_exists)
#
# for item in t_list:
# print(item)
# 2.kwargs 参数
# t_list =bs.find_all(id="head")
# t_list =bs.find_all(class_=True)
# 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") #根据id来查找
# t_list=bs.select("a[class='bri']") #通过属性来查找
# t_list=bs.select("head > title") #通过子标签来查找
# for item in t_list:
# print(item)
正则表达式:字符串模式(判断字符串是否符合要求)
在testRe.py中简单了解正则表达式
import re
#创建模式对象
pat = re.compile("AA") #此处的AA,是正则表达式,用来去校验其他的字符串
# m = pat.search("ABC") #search字符串是被校验的内容
# print(m)
# m=pat.search("ABCAA") #仅找到第一个符合的
# print(m)
#没有模式对象
# m=re.search("asd","Aasd") #前面的是规则(模板),后面是被校验的对象
# print(m)
# print(re.findall("a","AFAaKDFJaA")) #前面是规则(正则表达式),后面字符串是被校验的字符串 返回的是一个列表
# print(re.findall("[A-Z]","AFAaKDFJaA"))
# print(re.findall("[A-Z]+","AFAaKDFJaA"))
#sub
# print(re.sub("a","A","abcdcasd")) #找到a用A来替换
#建议在正则表达式中,被比较的字符串前面加一个r,不用担心转义字符的问题
# a=r"\nabd-\'"
# print(a)
# b="\nabd-\'"
# print(b)
完善spider.py中的逐一解析数据部分getData方法和正则规则的书写
正则提取和标签解析
# 影片详情超链接的规则
findLink=re.compile(r'<a href="(.*?)">') #创建正则表达式对象,表示规则(字符串的模式)
# 影片图片的链接规则
findImgSrc=re.compile(r'<img.*src="(.*?)"',re.S) #re.S 让换行符包含在字符中
# 影片的片名
findTitle = re.compile(r'<span class="title">(.*)</span>')
# 评分
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
# 评价人数
findJudge=re.compile(r'<span>(\d*)人评价</span>')
# 概况
findInq = re.compile(r'<span class="inq">(.*)</span>')
# 相关内容
findBd = re.compile(r'<p class="">(.*?)</p>',re.S)
#爬取网页
def getData(baseurl):
datalist=[]
for i in range(1): #调用获取页面信息的函数十次 改成10,此处打印一页25条
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)
#影片详情的超链接
link=re.findall(findLink,item)[0]
data.append(link)
imgSrc = re.findall(findImgSrc,item)[0]
data.append(imgSrc)
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(" ") #留空
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('<br(\s+)?/>(\s+)?'," ",bd) #去掉<br/>
bd = re.sub('/'," ",bd) #替换/
data.append(bd.strip()) #去掉前后的空格
datalist.append(data)
# print(datalist)
return datalist
把爬取到的数据写到excel文件中在testXlwt.py中学会简单的使用
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"%(j+1,i+1,(i+1)*(j+1)))
workbook.save('student.xls') #保存数据表
最终完整spider.py中的代码
爬取后写入excel文件中
# -*- codeing = utf-8 -*-
import sys
from bs4 import BeautifulSoup # 网页解析,获取数据
import re #正则,进行文字匹配
import urllib.request,urllib.error #制定url,获取网页数据
import xlwt #进行excel操作
import sqlite3
def main():
baseurl = 'https://movie.douban.com/top250?start='
#1.爬取网页
datalist = getData(baseurl)
savepath='豆瓣电影Top250.xls'
#3.保存数据
saveData(datalist,savepath)
# 影片详情超链接的规则
findLink=re.compile(r'<a href="(.*?)">') #创建正则表达式对象,表示规则(字符串的模式)
# 影片图片的链接规则
findImgSrc=re.compile(r'<img.*src="(.*?)"',re.S) #re.S 让换行符包含在字符中
# 影片的片名
findTitle = re.compile(r'<span class="title">(.*)</span>')
# 评分
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
# 评价人数
findJudge=re.compile(r'<span>(\d*)人评价</span>')
# 概况
findInq = re.compile(r'<span class="inq">(.*)</span>')
# 相关内容
findBd = re.compile(r'<p class="">(.*?)</p>',re.S)
#爬取网页
def getData(baseurl):
datalist=[]
for i in range(1): #调用获取页面信息的函数十次 改成10,此处打印一页25条
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)
#影片详情的超链接
link=re.findall(findLink,item)[0]
data.append(link)
imgSrc = re.findall(findImgSrc,item)[0]
data.append(imgSrc)
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(" ") #留空
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('<br(\s+)?/>(\s+)?'," ",bd) #去掉<br/>
bd = re.sub('/'," ",bd) #替换/
data.append(bd.strip()) #去掉前后的空格
datalist.append(data)
# print(datalist)
return datalist
#得到指定一个URL的网页内容
def askURL(url):
head={ # 模拟浏览器头部信息 (伪装)
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"
} #用户代理,表示告诉豆瓣服务器,我们是一个浏览器(本质上是告诉浏览器,我们可以接受什么水平的文件内容)
request = urllib.request.Request(url, headers=head)
html=""
try:
response=urllib.request.urlopen(request)
html=response.read().decode('utf-8')
# print(html)
except Exception as e:
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
return html
def saveData(datalist,savepath):
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,25):
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("爬取完成")
爬取后写入数据库文件中
# -*- codeing = utf-8 -*-
import sys
from bs4 import BeautifulSoup # 网页解析,获取数据
import re #正则,进行文字匹配
import urllib.request,urllib.error #制定url,获取网页数据
import xlwt #进行excel操作
import sqlite3
def main():
baseurl = 'https://movie.douban.com/top250?start='
#1.爬取网页
datalist = getData(baseurl)
# savepath='豆瓣电影Top250.xls'
dbpath="movie.db"
#3.保存数据
# saveData(datalist,savepath)
saveData2DB(datalist,dbpath)
# 影片详情超链接的规则
findLink=re.compile(r'<a href="(.*?)">') #创建正则表达式对象,表示规则(字符串的模式)
# 影片图片的链接规则
findImgSrc=re.compile(r'<img.*src="(.*?)"',re.S) #re.S 让换行符包含在字符中
# 影片的片名
findTitle = re.compile(r'<span class="title">(.*)</span>')
# 评分
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
# 评价人数
findJudge=re.compile(r'<span>(\d*)人评价</span>')
# 概况
findInq = re.compile(r'<span class="inq">(.*)</span>')
# 相关内容
findBd = re.compile(r'<p class="">(.*?)</p>',re.S)
#爬取网页
def getData(baseurl):
datalist=[]
for i in range(10): #调用获取页面信息的函数十次 改成10,此处打印一页25条
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)
#影片详情的超链接
link=re.findall(findLink,item)[0]
data.append(link)
imgSrc = re.findall(findImgSrc,item)[0]
data.append(imgSrc)
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(" ") #留空
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('<br(\s+)?/>(\s+)?'," ",bd) #去掉<br/>
bd = re.sub('/'," ",bd) #替换/
data.append(bd.strip()) #去掉前后的空格
datalist.append(data)
# print(datalist)
return datalist
#得到指定一个URL的网页内容
def askURL(url):
head={ # 模拟浏览器头部信息 (伪装)
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"
} #用户代理,表示告诉豆瓣服务器,我们是一个浏览器(本质上是告诉浏览器,我们可以接受什么水平的文件内容)
request = urllib.request.Request(url, headers=head)
html=""
try:
response=urllib.request.urlopen(request)
html=response.read().decode('utf-8')
# print(html)
except Exception as e:
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
return html
def saveData(datalist,savepath):
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) # 保存数据表
def saveData2DB(datalist,dbpath):
init_db(dbpath) #初始化 创数据库/打开数据库,建表
conn=sqlite3.connect(dbpath)
cur =conn.cursor()
for data in datalist:
for index in range(len(data)):
if index ==4 or index ==5:
continue
data[index]='"'+data[index]+'"'
sql = '''
insert into movie250(
info_link,pic_link,cname,ename,score,rated,introduction,info
)
values (%s)'''%",".join(data)
cur.execute(sql)
conn.commit()
cur.close()
conn.close()
def init_db(dbpath):
sql='''
create table movie250(
id integer primary key autoincrement,
info_link text,
pic_link text,
cname varchar,
ename varchar,
score numeric ,
rated numeric ,
introduction text,
info text
)
''' #创建数据表
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
conn.close()
if __name__ == '__main__': # 当程序执行时
main()
print("爬取完成")