爬取百度热搜


 

 

一、网络爬虫设计方案

1、爬虫名称:百度热搜

2、内容:爬取百度热搜排行榜和热度

3、概述:首先查找源代码,使用request进行请求后对数据进行清洗和处理。再使用BeautifulSoup等工具对数据可视化,最后进行小结。

难点:回归直线

二、页面结构与特征分析

1、

2、查看源代码

三、爬虫程序设计

1、数据爬取与采集

#导入相关库
import requests from bs4 import BeautifulSoup import pandas as pd from pandas import DataFrame import matplotlib.pyplot as plt import numpy as np import scipy as sp
import seaborn as sns def get_html(url,headers): r = requests.get(url,headers=headers) r.encoding = r.apparent_encoding return r.text def get_pages(html): soup = BeautifulSoup(html,'html.parser') all_topics=soup.find_all('tr')[1:] for each_topic in all_topics: topic_times = each_topic.find('td', class_='last') # 搜索指数 topic_rank = each_topic.find('td', class_='first') # 排名 topic_name = each_topic.find('td', class_='keyword') # 标题目 if topic_rank != None and topic_name != None and topic_times != None: topic_rank = each_topic.find('td', class_='first').get_text().replace(' ', '').replace('\n', '') topic_name = each_topic.find('td', class_='keyword').get_text().replace(' ', '').replace('\n', '') topic_times = each_topic.find('td', class_='last').get_text().replace(' ', '').replace('\n', '') # print('排名:{},标题:{},热度:{}'.format(topic_rank,topic_name,topic_times)) tplt = "排名:{0:^4}\t标题:{1:{3}^15}\t热度:{2:^8}" print(tplt.format(topic_rank, topic_name, topic_times, chr(12288))) def main(): #百度热点排行榜单链接 url = 'http://top.baidu.com/buzz?b=1&fr=20811' headers = {'User-Agent': 'Mozilla/5.0'} html = get_html(url, headers) get_pages(html) if __name__ == '__main__': main() #将数据存入excel文件中 df = pd.DataFrame([“排名”,“标题”,“热度”]) print(df) df.to_excel('D:/BaiDu.xlsx.') print(Done!)

 爬取的数据 

提取前五存入Excel中

 

2、进行数据清洗和处理

#数据清洗
BaiDu = pd.read_excel('D:/BaiDu.xlsx')
print(BaiDu.duplicated())
#重复值处理 print(BaiDu.insnull())
#空值与缺失值处理 print(BaiDu.describe())
#异常值处理

 

 

结果:

3、数据可视化

#饼图

label='1’,‘2’,‘3’,‘4’,‘5’ #排名前五
sizes=5344506,3774958,3552070,3485324,2844965 #热度
colors='yellow','green','gold','lightskyblu','lightcoral' #颜色
explode=0,0.1,0,0,0
plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.1f%%',shadow=True,startangle=50)
plt.axis('equal')
plt.show()

 结果:

#柱形图

# -*- coding: utf-8 -*-
plt.rcParams['font.sans-serif']=['Arial Unicode MS'] #正确显示中文
#正确显示正负号
plt.rcParams['axes.unicode_minus']=False name_list = ['1','2',‘3','4','5] num_list = [5344506,3774958,3552070,3485324,2844965] plt.bar(range(len(num_list)), num_list,color='rgb',tick_label=name_list) plt.show()

 

结果

 

#散点图

x = np.arange(1,5)
y =x
fig = plt.figure()
ax1 =fig.add_subplot(111)
#设置标题
ax1.set_title('BaiDu'
#设置X轴标签
plt.xlabel('rank')
#设置Y轴标签
plt.ylabel('hot‘)
#画散点图
ax1.scatter(x,y,c = 'r',marker = 'o')
#设置图标
plt.legend('x1')
plt.show()

 

结果

#回归直线

#导入相关库
import requests
from bs4 import BeautifulSoup
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
import numpy as np 
import scipy as sp
import seaborn as sns
 
def get_html(url,headers):
   r = requests.get(url,headers=headers)
   r.encoding = r.apparent_encoding
   return r.text
 
def get_pages(html):
   soup = BeautifulSoup(html,'html.parser')
   all_topics=soup.find_all('tr')[1:]
   for each_topic in all_topics:
       topic_times = each_topic.find('td', class_='last')  
# 搜索指数 topic_rank = each_topic.find('td', class_='first')
# 排名 topic_name = each_topic.find('td', class_='keyword')
# 标题目 if topic_rank != None and topic_name != None and topic_times != None: topic_rank = each_topic.find('td', class_='first').get_text().replace(' ', '').replace('\n', '') topic_name = each_topic.find('td', class_='keyword').get_text().replace(' ', '').replace('\n', '') topic_times = each_topic.find('td', class_='last').get_text().replace(' ', '').replace('\n', '') # print('排名:{},标题:{},热度:{}'.format(topic_rank,topic_name,topic_times)) tplt = "排名:{0:^4}\t标题:{1:{3}^15}\t热度:{2:^8}" print(tplt.format(topic_rank, topic_name, topic_times, chr(12288))) def main(): #百度热点排行榜单链接 url = 'http://top.baidu.com/buzz?b=1&fr=20811' headers = {'User-Agent': 'Mozilla/5.0'} html = get_html(url, headers) get_pages(html) if __name__ == '__main__': main() #将数据存入excel文件中 df = pd.DataFrame([“排名”,“标题”,“热度”]) print(df) df.to_excel('D:/BaiDu.xlsx.') print(Done!) #数据清洗 BaiDu = pd.read_excel('D:/BaiDu.xlsx') print(BaiDu.duplicated()) #重复值处理 print(BaiDu.insnull()) #空值与缺失值处理 print(BaiDu.describe()) #异常值处理 #饼图 label='1’,‘2’,‘3’,‘4’,‘5’
#排名前五 sizes=5344506,3774958,3552070,3485324,2844965 #热度 colors='yellow','green','gold','lightskyblu','lightcoral' #颜色 explode=0,0.1,0,0,0 plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.1f%%',shadow=True,startangle=50) plt.axis('equal') plt.show() #柱形图 # -*- coding: utf-8 -*- plt.rcParams['font.sans-serif']=['Arial Unicode MS'] #正确显示中文 #正确显示正负号 plt.rcParams['axes.unicode_minus']=False name_list = ['1','2',‘3','4','5] num_list = [5344506,3774958,3552070,3485324,2844965] plt.bar(range(len(num_list)), num_list,color='rgb',tick_label=name_list) plt.show() x = np.arange(1,5) y =x fig = plt.figure() ax1 =fig.add_subplot(111) #设置标题 ax1.set_title('BaiDu' #设置X轴标签 plt.xlabel('rank') #设置Y轴标签 plt.ylabel('hot‘) #画散点图 ax1.scatter(x,y,c = 'r',marker = 'o') #设置图标 plt.legend('x1') plt.show() sns.set_style('darkgrid')
#设置风格为暗 student=pd.read_excel('D:/BaiDu.xlsx') g=sns.FacetGrid(student,col_order='class',size=7
)#size为设置显示界面大小 g.map(plt.scatter,'momheight','height',s=140,linewidth=.7,edgecolor='red',color='#ff8000')
#edgecolor为全边颜色,color为圈内颜色 g.set_axis_labels('hot','rank')
#设置标题 plt.show() #盒图 sns.set(style="ticks") tips = sns.load_dataset("tips) #绘图 sns.boxplot(x="hot",y="rank"),data=tips,palette="PRGn') sns.despine(offset=10,trim=True) #图片显示 pyplot.savefig("GroupBoxplots.png") pyplot.show()

 

 

 四、结论:人们对娱乐方面更感兴趣,且也同时关注着全国疫情的情况。

小结:经过爬虫学习后,发现很多很实用很有趣的工具。回归方程对于我来说还是有难度的!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM