豆瓣图书Top250
生活随笔
收集整理的這篇文章主要介紹了
豆瓣图书Top250
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
從豆瓣圖書(shū)Top250抓取數(shù)據(jù),并通過(guò)詞云圖展示
導(dǎo)入庫(kù)
from lxml import etree #解析庫(kù) import time #時(shí)間 import random #隨機(jī)函數(shù) import pandas as pd import requests #請(qǐng)求庫(kù) import jieba #導(dǎo)入結(jié)巴分詞 from pyecharts.charts import WordCloud from pyecharts import options as opts抓取數(shù)據(jù)
#循環(huán)構(gòu)造網(wǎng)址 def format_url(base_url,pages=10):urls=[]for num in range(0,pages * 25,25):urls.append(base_url.format(num))return urls#解析單個(gè)頁(yè)面 def parse_page(url,headers):#創(chuàng)建一個(gè)存儲(chǔ)結(jié)果的容器result=pd.DataFrame()html=requests.get(url,headers=headers)bs=etree.HTML(html.text)for i in bs.xpath('//tr[@class="item"]'):#書(shū)籍中文名book_ch_name=i.xpath('td[2]/div[1]/a[1]/@title')[0]#評(píng)分score=i.xpath('td[2]/div[2]/span[2]')[0].text#書(shū)籍信息book_info=i.xpath('td[2]/p[@class="pl"]')[0].text#評(píng)價(jià)數(shù)量由于數(shù)據(jù)不規(guī)整,使用字符串方法進(jìn)行數(shù)據(jù)處理comment_num=i.xpath('td[2]/div[2]/span[3]')[0].text.replace(' ','').strip('(\n').strip('\n)')try:#一句話概括brief=i.xpath('td[2]/p[@class="quote"]/span')[0].textexcept:brief=None#這里的cache是存儲(chǔ)每一循環(huán)的結(jié)果,然后通過(guò)下一步操作循環(huán)更新result里面的數(shù)據(jù)cache=pd.DataFrame({'中文名':[book_ch_name],'評(píng)分':[score],'書(shū)籍信息':[book_info],'評(píng)價(jià)數(shù)量':[comment_num],'一句話概括':[brief]})result=pd.concat([result,cache])return result#主函數(shù) def main():final_result=pd.DataFrame()base_url='https://book.douban.com/top250?start={}'headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}urls=format_url(base_url,pages=10)for url in urls:res=parse_page(url,headers=headers)final_result=pd.concat([final_result,res])time.sleep(random.random()*3)return final_result#運(yùn)行函數(shù) if __name__ == "__main__":final_result = main()提取詞云圖要展示的數(shù)據(jù)
#提取書(shū)名、評(píng)分、評(píng)價(jià)數(shù)量 book_top250=final_result[['中文名','評(píng)分','評(píng)價(jià)數(shù)量']]#將書(shū)名轉(zhuǎn)為列表 book_name=book_top250['中文名'].tolist()#將評(píng)分轉(zhuǎn)為列表 book_score=book_top250['評(píng)分'].tolist()#將評(píng)價(jià)人數(shù)轉(zhuǎn)為列表 book_comment_num=book_top250['評(píng)價(jià)數(shù)量'].tolist() #去除多余字符"人評(píng)價(jià)" book_comment_num=[x.strip("人評(píng)價(jià)") for x in book_comment_num if x.strip()!='']#用for循環(huán)合并數(shù)據(jù) a=[z for z in zip(book_name,book_comment_num)]繪圖設(shè)置
c=(#WordCloud類的實(shí)例化WordCloud()#添加圖名稱、數(shù)據(jù)、字體的隨機(jī)大小、圖像類型.add("",a,word_size_range=[5,50],shape="diamond")#設(shè)置標(biāo)題.set_global_opts(title_opts=opts.TitleOpts(title="豆瓣圖書(shū)Top250")) )結(jié)果展示
c.render_notebook()參考來(lái)源:
微信公眾號(hào):數(shù)據(jù)不吹牛(shujubuchuiniu)
https://blog.csdn.net/weixin_40864434/article/details/90301592
轉(zhuǎn)載于:https://www.cnblogs.com/hankleo/p/11408811.html
總結(jié)
以上是生活随笔為你收集整理的豆瓣图书Top250的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 在华为MateBook Ego的arm
- 下一篇: 阿里巴巴网站的搜索引擎优化案例分析