准備工作
1、進入豆瓣網圖書頻道:https://book.douban.com
2、尋找感興趣的圖書,進入其頁面並查看該圖書的評論
3、分析評論數據URL地址特性,得到其共有部分為:https://book.douban.com/subject/book_id/comments?
其中book_id為圖書在網頁地址欄中的編號
編碼實現爬蟲
# 獲取HTML頁面 def getHtml(url): try: r = requests.get(url, timeout=30) r.raise_for_status() return r.text except: return '' # 獲取評論 def getComment(html): soup = BeautifulSoup(html, 'html.parser') comments_list = [] # 評論列表 comment_nodes = soup.select('.comment > p') for node in comment_nodes: comments_list.append(node.get_text().strip().replace("\n", "") + u'\n') return comments_list # 獲取並將評論保存到文件中 def saveCommentText(fpath): pre_url = "https://book.douban.com/subject/1799652/comments?" # 爬取深度 depth = 16 with open(fpath, 'w', encoding='utf-8') as f: for i in range(depth): print('開始爬取第{}頁評論...'.format(i)) url = pre_url + 'start=' + str(20 * i) + '&limit=20&sort=new_score&' + 'status=P' html = getHtml(url) f.writelines(getComment(html)) # 設置隨機休眠防止IP被封,好像也沒有必要 time.sleep(1 + float(random.randint(1, 20)) / 20)
生成詞雲
詞雲的生成要使用wordcloud組件
此外要指定背景圖片,以及文字字體文件資源路徑,否則中文無法顯示
此外還要進行切詞操作
切詞
# 切詞 def cutWords(fpath): text = '' with open(fpath, 'r', encoding='utf-8') as fin: for line in fin.readlines(): line = line.strip('\n') text += ' '.join(jieba.cut(line)) text += ' ' with codecs.open('cut_word.txt', 'w', encoding='utf-8') as f: f.write(text) print("\n分詞完成,文件保存成功!")
創建詞雲圖片
# 繪制詞雲 def drawWordcloud(): with codecs.open('cut_word.txt', encoding='utf-8') as f: comment_text = f.read() color_mask = imread("comment.jpeg") # 讀取背景圖片 Stopwords = [u'就是', u'作者', u'你們', u'這么', u'不過', u'但是', u'什么', u'沒有', u'這個', u'那個', u'大家', u'比較', u'看到', u'真是', u'除了', u'時候', u'已經', u'可以', u','u'。'] cloud = WordCloud(font_path="FZYTK.TTF", # 中文字體,否則無法顯示 background_color='white', max_words=200, max_font_size=200, min_font_size=4, mask=color_mask, stopwords=Stopwords) word_cloud = cloud.generate(comment_text) # 產生詞雲 image_colors = ImageColorGenerator(color_mask) # 以下代碼顯示圖片 plt.imshow(cloud) plt.axis("off") # 繪制詞雲 plt.figure() # 重新着色,使用背景圖片中的顏色 plt.imshow(cloud.recolor(color_func=image_colors)) plt.axis("off") # 繪制背景圖片為顏色的圖片 plt.figure() plt.imshow(color_mask, cmap=plt.cm.gray) plt.axis("off") plt.show() # 保存圖片 word_cloud.to_file("comment_cloud.jpg") print('詞雲圖保存成功')
運行結果: