python高级应用第五次作业:爬取百度热搜榜
首先打开要爬取的网址,查看源代码
找到要爬取的数据
import requests from bs4 import BeautifulSoup import bs4 import pandas as pd titles=[] hots=[] url='http://top.baidu.com/buzz?b=341&c=513&fr=topbuzz_b1_c513' #选择要爬取的网站 headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/69.0.3497.100 Safari/537.36'}#伪装爬虫 r=requests.get(url) #获得url信息 r.raise_for_status() #失败请求(非200响应)抛出异常 r.encoding = r.apparent_encoding #根据内容分析出的编码方式,备选编码; html = r.text #获得的HTML文本 table = BeautifulSoup(html,"html.parser").find("table") #对获得的文本进行html解析,查找<table>内的信息 soup=BeautifulSoup(html,'lxml') for m in soup.find_all(class_="keyword"): titles.append(m.get_text().strip()) for n in soup.find_all(class_="icon-rise"): hots.append(n.get_text().strip()) final=[titles,hots] print(final) s=pd.DataFrame(final,index=["标题","热度数据"]) #使用工具使其可视化 print(s.T)

浙公网安备 33010602011771号