python爬取熱搜制作詞云
環(huán)境:win10,64位,mysql5.7數(shù)據(jù)庫,python3.9.7,ancod
邏輯流程:
- 1、首先爬取百度熱搜,至少間隔1小時(shí)
- 2、存入文件,避免重復(fù)請(qǐng)求,如果本1小時(shí)有了不再請(qǐng)求
- 3、存入數(shù)據(jù)庫,供詞云包使用
- 1、爬取熱搜,首先拿到
url,使用的包urllib,有教程說urllib2是python2的。
'''讀取頁面'''
def readhtml(self,catchUrl):
catchUrl=self.catchUrl if not catchUrl else catchUrl
response=urllib.request.urlopen(catchUrl)
text=response.read().decode(self.bmcode)
return text
這里在本類定義了幾個(gè)屬性,上述self的就是,這不是重點(diǎn),繼續(xù),上述使用了三目運(yùn)算符
'''生成時(shí)間'''
def createTime(self):
# 格式化成2016-03-20 11:45:39形式
return time.strftime("%Y%m%d%H", time.localtime())
'''寫入文件'''
def write2file(self,text):
fileName=self.writePosition+self.createTime()+'.txt'
self.fileName=fileName
print(fileName)
#判斷路徑,不存在生成
if not os.path.exists(self.writePosition):
os.mkdir(self.writePosition )
if os.path.exists(fileName):
uuid_tools().printlog('已經(jīng)存在:{}'.format(fileName))
return self.fileName
mode='a' if os.path.exists(fileName) else 'w'
with open(fileName,mode,encoding=self.bmcode) as f:
f.write(text)
print("寫入{} 完成".format(fileName))
return self.fileName
這里每個(gè)小時(shí)生成一個(gè)文件名稱,避免了重復(fù),如果這一小時(shí)里已經(jīng)抓取過了,那么不再抓取了。
這里使用了日志(需導(dǎo)入日志包import logging):
'''打印日志'''
def printlog(self,loginfo):
logging.basicConfig(level=logging.INFO)
logging.info(loginfo)
獲取到內(nèi)容后,這里需要去掉<div>xxx</div>這個(gè)東西,還有個(gè)查看更多
'''去掉標(biāo)簽'''
def removeBq(self,content):
pat=re.compile('>(.*?)<')
str=''.join(pat.findall(content))
str=str.replace(' 查看更多> ','')
return str
'''輸出內(nèi)容'''
def printContent(self, o,class_name):
print(self.removeBq(str(o.find(class_=class_name))))
這里是beautifulsoup分析html格式的內(nèi)容:
'''測(cè)試獲取某個(gè)片段'''
def readFilePd(self,fileName):
#fileName='d:\\bdrs\\2021122010.txt'
jt=open(fileName,'r',encoding=self.bmcode)
try:
content=jt.read()
soup=BeautifulSoup(content,"html.parser")
rs=RsBean()
for k in soup.find_all('div',class_=rs.alldiv):
print( str(k))
# self.printContent(k,rs.sx)
# self.printContent(k,rs.bt)
# self.printContent(k,rs.ms)
# self.printContent(k,rs.rszs)
except Exception as e:
print('error:'+str(e))
最主要的是這一句:soup.find_all('div',class_='xxx')尤其這個(gè)橫杠,是該方法參數(shù),代表標(biāo)簽的class名稱。
最后插入數(shù)據(jù)庫,
'''打開連接'''
def open(self):
self.db=pymysql.connect(host=self.host,port=3306,user=self.user,passwd=self.passwd,db=self.database)
#創(chuàng)建游標(biāo)
self.cursor=self.db.cursor()
#print("打開連接成功")
#關(guān)閉
def close(self):
self.cursor.close()
self.db.close()
#print("close連接成功")
def execute(self,sql,list=[]):
try:
self.open()
self.cursor.execute(sql,list)
self.db.commit()
print("execute successfully!")
except Exception as e:
self.db.rollback()
print("Execute failure!",str(e))
self.close()
封裝的代碼,后邊這樣使用:
'''讀取文件'''
def readFile(self,fileName):
#fileName='d:\\bdrs\\2021122010.txt'
jt=open(fileName,'r',encoding=self.bmcode)
try:
content=jt.read()
soup=BeautifulSoup(content,"html.parser")
rs=RsBean()
daoOper=OperateRsDao()
rs_shijian=self.cutfilename(fileName)
#先清空
self.clearBefore(daoOper,rs_shijian)
#讀取文件
for k in soup.find_all('div',class_=rs.alldiv):
#插入數(shù)據(jù)
rs.rs_shijian=rs_shijian
self.insertData(daoOper,k,rs)
except Exception as e:
print('error:'+str(e))
最后詞云顯示:
if __name__ == '__main__':
a=db_connect()
sql='select id,shun_xu,biao_ti,miao_shu,reshou_zhishu,insert_time,rs_shijian from bdrs_one order by rs_shijian desc,shun_xu asc '
result=a.select(sql)
jieguo=''
for m in result:
print(m)
jieguo+=m[2]
#根據(jù)title做詞云
CiYun().showImage(jieguo)
效果:

可以看出最大的瓜是啥。
到此這篇關(guān)于python爬取百度熱搜制作詞云的文章就介紹到這了,更多相關(guān)python爬取熱搜制作詞云內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的古詩生成器
這篇文章主要為大家詳細(xì)介紹了基于循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的古詩生成器,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03
python中scipy.stats產(chǎn)生隨機(jī)數(shù)實(shí)例講解
在本篇文章里小編給大家分享的是一篇關(guān)于python中scipy.stats產(chǎn)生隨機(jī)數(shù)實(shí)例講解內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。2021-02-02
Python?pyecharts數(shù)據(jù)可視化實(shí)例詳解
PyEcharts是一個(gè)用于生成?Echarts圖表的類庫,?Python是一門富有表達(dá)力的語言,很適合用于數(shù)據(jù)處理,下面這篇文章主要給大家介紹了關(guān)于Python?pyecharts數(shù)據(jù)可視化的相關(guān)資料,需要的朋友可以參考下2022-05-05
Python使用Numpy實(shí)現(xiàn)Kmeans算法的步驟詳解
將物理或抽象對(duì)象的集合分成由類似的對(duì)象組成的多個(gè)類的過程被稱為聚類。這篇文章主要介紹了Python使用Numpy實(shí)現(xiàn)Kmeans算法,需要的朋友可以參考下2021-11-11

