python爬取博客园
一、爬虫简介:
网络爬虫(又称为网页蜘蛛,网络机器人,在 FOAF 社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的 程序 或者 脚本 。 另外一些不常使用的名字还有蚂蚁、自动索引、模拟程序或者蠕虫。
二、需求
期末临近,学院老师让我们每个人导出自己博客园写过的博客,当然我是一个初学python爬虫的懒人,就决定用爬虫来试试。
我需要的是爬取我的个人博客的主页的博客标题、链接、概要、点赞评论数等,我决定先爬十页试试水。
三、流程分析
第一步 找地址
我们需要找到自己的博客地址,比如我的主页地址是这个https://www.cnblogs.com/wjingbo/,不过我需要爬取的并不是他一页,当我点击下一页的时候,他变成了这样https://www.cnblogs.com/wjingbo/default.html?page=2,显然这个page2便是第二页,这时候规律来了,我们只需要一个循环每次+1便能完成爬取每一个页。
第二步 分析网页
我们分析这个网页,然后找到自己想要的信息在哪。这时候我们按下F12或者右键页面选择检查,查看页面元素。

然后我们会发现标题在span标签中,链接在一个a标签中,这时候我们找到我们全部需要的信息的位置,然后通过python现有的库,来进行爬取内容。
第三步 分析数据
我们爬取完数据会发现他并不是我们单纯想要的数据,会有很多换行符、空格、一些杂七杂八的标签,我们这时候就需要python的re库进行正则的过滤,过滤出我们自己想要的信息。
第四步 保存数据
我们数据已经爬取完了全部存到了一个列表当中,这时候我们需要保存的我们的数据到excel中,这时候我们需要用到python的操作excel的库进行操作。
四、代码分解
①引入需要的库
from bs4 import BeautifulSoup #网页解析
import re #正则表表达式文字匹配
import urllib.request,urllib.error #指定url,获取网页数据
import xlwt #进行excel操作
②向网页请求数据
def askURL(url):
head = { #伪装请求头,模拟浏览器访问
"User-Agent":" Mozilla / 5.0(Linux;Android6.0;Nexus5 Build / MRA58N) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 99.0.4844.51Mobile 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 urllib.error.URLError as e: #异常处理
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
return html #返回爬到所有的html数据
③分析数据(难点)
这部分需要的知识量较大一些,可以着重学一下正则表达式。
#正则表达式控制获取详细内容
findTitle = re.compile(r'<span>(.*?)</span>',re.S)
findlink = re.compile(r'<a class="postTitle2 vertical-middle" href="(.*?)">')
findzhaiyao = re.compile(r'<div class="c_b_p_desc"(.*?)<a',re.S)
finddate = re.compile(r'<div class="postDesc">posted @(.*?)权',re.S)
findread = re.compile(r'<span class="post-view-count" data-post-id=(.*?)</span>')
findcomment = re.compile(r'<span class="post-comment-count" data-post-id=(.*?)</span>')
finddigg = re.compile(r'<span class="post-digg-count" data-post-id=(.*?)</span>')
获取数据函数。
def getData(baseurl):
datalist = [] # 2 解析数据
allTitle = [] #存储标题
allLink = [] #存储链接
allZhaiyao = [] #存储摘要
alldate = [] #存储日期
allRead = [] #存储阅读数
allComment = [] #存储评论数
allDigg = [] #存储推荐数
for i in range(0,10):
url = baseurl + str(i+1) #对目标链接地址page=后面的数字进行循环
html = askURL(url) #调用爬取函数
soup = BeautifulSoup(html, "html.parser")
for item in soup.find_all('div',class_="day"): #简单过滤信息
#print(item)
item = str(item)
title = re.findall(findTitle,item) #匹配数据
allTitle.extend(title) #添加数据到列表
link = re.findall(findlink,item)
allLink.extend(link)
zhaiyao = re.findall(findzhaiyao,item)
allZhaiyao.extend(zhaiyao)
date = re.findall(finddate,item)
alldate.extend(date)
readNum = re.findall(findread,item)
allRead.extend(readNum)
commentNum = re.findall(findcomment,item)
allComment.extend(commentNum)
diggNum = re.findall(finddigg,item)
allDigg.extend(diggNum)
#print(allTitle)
#print(allLink)
#print(allZhaiyao)
#print(alldate)
#print(allRead)
#print(allComment)
#print(allDigg)
for j in range(0,100): #循环10页就是100条数据,这个循环是过滤掉所有不需要的信息
data = []
title = allTitle[j].strip() #去除字符串里的空格
data.append(title)
link = allLink[j]
data.append(link)
zhaiyao = allZhaiyao[j].strip()
zhaiyao = zhaiyao.split('">')[1]
data.append(zhaiyao.replace("\n",""))
date = alldate[j].strip()
data.append(date)
readNum = allRead[j].split('>')[1] #通过分割字符串来去除无用信息
data.append(readNum)
commentNum = allComment[j].split('>')[1]
data.append(commentNum)
diggNum = allDigg[j].split('>')[1]
data.append(diggNum)
datalist.append(data)
print(datalist)
return datalist #返回列表
这部分比较麻烦,我大概调试了3个小时。
④保存数据
def saveData(datalist,savepath):
print("save...")
book = xlwt.Workbook(encoding="utf-8",style_compression=0)
sheet = book.add_sheet('博客园随笔列表',cell_overwrite_ok=True) #创建sheet1
col = ("标题","原文链接","摘要","时间","阅读","评论","推荐") #加标题
for i in range(0,7):
sheet.write(0,i,col[i])
for i in range(0,100): #添加数据到excel*(100条)
print("第%d条"%(i+1)) #打印条数
data = datalist[i]
for j in range(0,7):
sheet.write(i+1,j,data[j]) #添加每个子列表中的7个数据
book.save(savepath) #保存excel
⑤主函数
def main():
baseurl = "https://www.cnblogs.com/wjingbo/default.html?page="
datalist = getData(baseurl) #调研分析数据函数
#1 爬取网页
savepath = ".\\权。的博客信息.xls" #excel保存的位置名称
saveData(datalist,savepath) #调用保存函数
⑥设置程序入口
if __name__ == "__main__":
main()
print("爬取完毕!")
到这里就完成爬取工作了。
五、完整源代码
# -*- coding = utf-8 -*-
# @Time : 2022/4/27 8:21
# @Author :王敬博
# @File : test.py
# @Software: PyCharm
from bs4 import BeautifulSoup #网页解析
import re #正则表表达式文字匹配
import urllib.request,urllib.error #指定url,获取网页数据
import xlwt #进行excel操作
import sqlite3 #进行SQLite数据库操作
import pymysql.cursors #连接mysql数据库
def main():
baseurl = "https://www.cnblogs.com/wjingbo/default.html?page="
datalist = getData(baseurl) #调研分析数据函数
#1 爬取网页
savepath = ".\\权。的博客信息.xls" #excel保存的位置名称
saveData(datalist,savepath) #调用保存函数
def askURL(url):
head = { #伪装请求头,模拟浏览器访问
"User-Agent":" Mozilla / 5.0(Linux;Android6.0;Nexus5 Build / MRA58N) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 99.0.4844.51Mobile 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 urllib.error.URLError as e:
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
return html #返回爬到所有的html数据
#正则表达式控制获取详细内容
findTitle = re.compile(r'<span>(.*?)</span>',re.S)
findlink = re.compile(r'<a class="postTitle2 vertical-middle" href="(.*?)">')
findzhaiyao = re.compile(r'<div class="c_b_p_desc"(.*?)<a',re.S)
finddate = re.compile(r'<div class="postDesc">posted @(.*?)权',re.S)
findread = re.compile(r'<span class="post-view-count" data-post-id=(.*?)</span>')
findcomment = re.compile(r'<span class="post-comment-count" data-post-id=(.*?)</span>')
finddigg = re.compile(r'<span class="post-digg-count" data-post-id=(.*?)</span>')
def getData(baseurl):
datalist = [] # 2 解析数据
allTitle = [] #存储标题
allLink = [] #存储链接
allZhaiyao = [] #存储摘要
alldate = [] #存储日期
allRead = [] #存储阅读数
allComment = [] #存储评论数
allDigg = [] #存储推荐数
for i in range(0,10):
url = baseurl + str(i+1) #对目标链接地址page=后面的数字进行循环
html = askURL(url) #调用爬取的函数
soup = BeautifulSoup(html, "html.parser")
for item in soup.find_all('div',class_="day"): #简单过滤信息
#print(item)
item = str(item)
title = re.findall(findTitle,item) #匹配数据
allTitle.extend(title) #添加数据到列表
link = re.findall(findlink,item)
allLink.extend(link)
zhaiyao = re.findall(findzhaiyao,item)
allZhaiyao.extend(zhaiyao)
date = re.findall(finddate,item)
alldate.extend(date)
readNum = re.findall(findread,item)
allRead.extend(readNum)
commentNum = re.findall(findcomment,item)
allComment.extend(commentNum)
diggNum = re.findall(finddigg,item)
allDigg.extend(diggNum)
#print(allTitle)
#print(allLink)
#print(allZhaiyao)
#print(alldate)
#print(allRead)
#print(allComment)
#print(allDigg)
for j in range(0,100): #循环10页就是100条数据,这个循环是过滤掉所有不需要的信息
data = []
title = allTitle[j].strip() #去除字符串里的空格
data.append(title)
link = allLink[j]
data.append(link)
zhaiyao = allZhaiyao[j].strip()
zhaiyao = zhaiyao.split('">')[1]
data.append(zhaiyao.replace("\n",""))
date = alldate[j].strip()
data.append(date)
readNum = allRead[j].split('>')[1] #通过分割字符串来去除无用信息
data.append(readNum)
commentNum = allComment[j].split('>')[1]
data.append(commentNum)
diggNum = allDigg[j].split('>')[1]
data.append(diggNum)
datalist.append(data)
print(datalist)
return datalist #返回列表
def saveData(datalist,savepath):
print("save...")
book = xlwt.Workbook(encoding="utf-8",style_compression=0)
sheet = book.add_sheet('博客园随笔列表',cell_overwrite_ok=True) #创建sheet1
col = ("标题","原文链接","摘要","时间","阅读","评论","推荐") #加标题
for i in range(0,7):
sheet.write(0,i,col[i])
for i in range(0,100): #添加数据到excel*(100条)
print("第%d条"%(i+1)) #打印条数
data = datalist[i]
for j in range(0,7):
sheet.write(i+1,j,data[j]) #添加每个子列表中的7个数据
book.save(savepath) #保存excel
if __name__ == "__main__":
main()
print("爬取完毕!")
六、效果展示
到这里就结束了,如果有什么不懂的问题,可以私信我哦!如果对你有帮助记得点赞哦!
注:禁止商业转载,非商业转载须注明地址,谢谢合作。