頁面分析
1.在瀏覽器中輸入百度熱搜風雲網網址http://top.baidu.com/buzz?b=1&fr=topindex,點擊今日熱搜
2.查看頁面源代碼,查詢需要的標簽屬性關鍵字
3.程序實現
import requests from bs4 import BeautifulSoup import pandas as pd url = 'http://top.baidu.com/buzz?b=341&c=513' #爬蟲請求頭信息 headers = {'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'} #發起一個GET請求 res=requests.get(url,timeout=30) res.encoding=res.apparent_encoding#設置編碼標准 soup=BeautifulSoup(res.text,'html.parser')#采用BeautifulSoup類解析網頁,使用html.parser解析器 #創建列表 list1=[] list2=[] for x in soup.find_all('td',class_="keyword"):#for語句查找標簽 list1.append(x.get_text().strip()) for y in soup.find_all('td',class_= "last"):#for語句查找標簽 list2.append(y.get_text().strip()) data=[list1,list2] df=pd.DataFrame(data,index=["關鍵詞","搜索指數"]) print(df.T)
4.獲取數據