1,获取博客园链接:
https://www.cnblogs.com/
发现加载更多的博客的方式是加载下一页
同时我们点击下面的页数,博客园的链接是规律变化的:
https://www.cnblogs.com/#p3
点击第三页,#p后面即为页数,我们可以利用这一页数,来获取200页的网页链接,具体代码为:
url="https://www.cnblogs.com/"
def get_html(url): #获取博客园的200个主页面的链接并一一爬取存入列表中
html_list=[]
for i in range(1,201):
#for i in range(1,2):
r=requests.get(url+"/#p"+str(i))
r.encoding=r.apparent_encoding
html_list.append(BeautifulSoup(r.text,"html.parser"))
return html_list
2,提取博客信息
接下来,就是要获取其中的每一个博客的信息,查看网页源代码,看需要的信息在哪,用beautifulSoup库处理网页源代码,想尽办法提取所要的信息下面是信息提取代码:
def get_text(html): #爬取一个博客的信息存储在一个字典中,然后把所有字典存储在一个列表中
dict={
"名字":" ",
"标题":" ",
"阅读量":" ",
"评论数":" "
}
text_list = html.find_all("div", class_=re.compile('post_item'))
for i in range(len(text_list)):
try:
text1=text_list[i]
dict["标题"] = text1.h3.a.string
dict["名字"] = text1.div.a.string
dict["阅读量"] = text1.div.contents[4].a.string[3:-1]
dict["评论数"] = text1.div.span.a.string[13:-1]
need_list.append(dict.copy()) #此处为什么用copy()可以看我上一篇博客
except AttributeError:
continue
return need_list
列表中写入字典博客链接
3,将爬去的信息写入excel表格中
我是用xlsxwriter库来进行操作的
def write_xlsx(need_list): #将爬取的信息写入excel表中
workbook = xlsxwriter.Workbook('excel.xlsx')
worksheet = workbook.add_worksheet('Sheet1')
for i in range(1,len(need_list)):
worksheet.write('A'+str(i), need_list[i]["标题"])
worksheet.write('B'+str(i), need_list[i]["名字"])
worksheet.write('C'+str(i), need_list[i]["阅读量"])
worksheet.write('D'+str(i), need_list[i]["评论数"])
print("yes")
workbook.close()
这样就完成操作啦!
最后,给出源代码:
import requests
from bs4 import BeautifulSoup
import re
import xlsxwriter
need_list=[]
url="https://www.cnblogs.com/"
def get_html(url): #获取博客园的200个主页面的链接并一一爬取存入列表中
html_list=[]
for i in range(1,201):
#for i in range(1,2):
r=requests.get(url+"/#p"+str(i))
r.encoding=r.apparent_encoding
html_list.append(BeautifulSoup(r.text,"html.parser"))
return html_list
def get_text(html): #爬取一个博客的信息存储在一个字典中,然后把所有字典存储在一个列表中
dict={
"名字":" ",
"标题":" ",
"阅读量":" ",
"评论数":" "
}
text_list = html.find_all("div", class_=re.compile('post_item'))
for i in range(len(text_list)):
try:
text1=text_list[i]
dict["标题"] = text1.h3.a.string
dict["名字"] = text1.div.a.string
dict["阅读量"] = text1.div.contents[4].a.string[3:-1]
dict["评论数"] = text1.div.span.a.string[13:-1]
need_list.append(dict.copy()) #此处为什么用copy()可以看我上一篇博客
except AttributeError:
continue
return need_list
def get(html_list): #获取200个页面的所有博客信息
for i in range(len(html_list)):
#for i in range(1):
html=html_list[i]
get_text(html)
def write_xlsx(need_list): #将爬取的信息写入excel表中
workbook = xlsxwriter.Workbook('excel.xlsx')
worksheet = workbook.add_worksheet('Sheet1')
for i in range(1,len(need_list)):
worksheet.write('A'+str(i), need_list[i]["标题"])
worksheet.write('B'+str(i), need_list[i]["名字"])
worksheet.write('C'+str(i), need_list[i]["阅读量"])
worksheet.write('D'+str(i), need_list[i]["评论数"])
print("yes")
workbook.close()
def main():
html_list=get_html(url)
get(html_list)
write_xlsx(need_list)
main()