上图就是百度实时热点的界面,本次的任务就是爬取到排行榜上的前50排名的关键词以及它的搜索指数。
用到的库:1、selenium
2、BeautifulSoup
3、xlwt
(一):分析:
爬取一个网页的首要工作是分析网页的源代码:
可以看到tr标签里面就有我们想要的东西,排名,关键词,搜索指数
tr标签里面的三个class属性为:first,keyword,last的td标签便是我们要爬取的对象
我们只需要先把每个tr标签爬取下来,然后再从每个tr标签里面提取出三个td标签就可以了
td标签里面的子标签就有我们想要的内容
当然不是所有的tr标签都包含这三个td标签,所以需要筛选
需要注意一点的是 在最后的last标签里面由于排名有上升和下降
所以td标签里面的span标签的class属性的值可能有两种一种是fair另一种是rise
所以待会爬下来的时候筛选即可
(二)代码:
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import xlwt
#打开网页
url="http://top.baidu.com/buzz?b=1&fr=topindex"
driver = webdriver.Chrome()
driver.get(url)
#time.sleep(5)
#获取网页信息
html=driver.page_source
soup=BeautifulSoup(html,'lxml')
#用soup来获得所有'tr'标签
list=soup.find_all('tr')
result=[]
#将所有符合规则的'tr'标签里面的内容提取出来
for each in list:
rank = each.find('span')
key = each.find('a',{'class':'list-title'})
point = each.find('td',{'class':'last'})
if point !=None:
point = point.find('span')
if rank!=None and key!=None and point!=None :
result.append([rank.string,key.string,point.string])
#新建xls对象
workbook = xlwt.Workbook(encoding = 'utf-8')
worksheet = workbook.add_sheet('Baidu Rank Data')
worksheet.write(0,0, label = 'rank')
worksheet.write(0,1, label = 'key')
worksheet.write(0,2, label = 'point')
#设置列宽
col = worksheet.col(1)
col.width=5000
#写入数据
i=1
for each in result:
rank=str(each[0])
key=str(each[1])
point=str(each[2])
worksheet.write(i,0,rank)
worksheet.write(i,1,key)
worksheet.write(i,2,point)
i+=1
#保存
workbook.save(r'C:\Users\me\Desktop\Data.xls')
print(result)
#print(len(result))
#print(len(list))
(三)结果:
我用的是xlwt类输出了一个excel文档里面有爬取的内容,如下图所示
这样就把百度实时热搜榜的前50关键词及其指数爬取下来了