一、學(xué)習(xí)思路
(一)在學(xué)習(xí)selenium庫(kù)時(shí),看到一種使用方法
1、使用selenium獲取網(wǎng)頁(yè)
2、用BeautifulSoup來(lái)解析和獲取數(shù)據(jù)
(二)該方法的原理是:
1、selenium把element打開(kāi)就加載了所有的源代碼
2、HTML源代碼字符串=driver.page_source? #獲取完整渲染的網(wǎng)頁(yè)源代碼,它獲取結(jié)果數(shù)據(jù)類(lèi)型是字符串
3、用BS把字符串格式解析為BeautifulSoup對(duì)象
(三)實(shí)操
1、代碼如下:
from selenium import webdriver
import time
from bs4 import BeautifulSoup
import openpyxl
#引進(jìn)所需要的模塊
wb=openpyxl.Workbook()
sheet=wb.active
sheet.title='百度指數(shù)'
sheet.append(['序號(hào)','關(guān)鍵詞','熱點(diǎn)'])
#新建一個(gè)excel來(lái)保存后續(xù)數(shù)據(jù)
driver=webdriver.Chrome()
driver.get('http://top.baidu.com/buzz?b=1&c=513&fr=topcategory_c513')
time.sleep(3)
html=driver.page_source
time.sleep(5)
res=BeautifulSoup(html,'lxml')
lists=res.find_all('tr')
for list in lists:
? ? num=list.find('span')
? ? key=list.find('a',class_='list-title')
? ? hotpoint=list.find('td',class_='last')
? ? #在last標(biāo)簽里面由于排名有上升和下降? 所以td標(biāo)簽里面的span標(biāo)簽的class屬性的值不唯一,所以需要選擇更高一級(jí)的標(biāo)簽??
? ? if hotpoint !=None:
? ? ? ? hotpoint=hotpoint.find('span')
? ? if num!=None and key!=None and hotpoint!=None :
? ? ? ? rank=num.text
? ? ? ? key=key.text
? ? ? ? point=hotpoint.text
#此處的判斷是基于一些結(jié)果中的空值,將其去掉
? ? ? ? sheet.append([rank,key,point])
wb.save('百度熱點(diǎn).xlsx')