今天初试爬虫来爬取平凡的世界这本书再豆瓣的点赞数最多的排行。
import re
from collections import Counter
import requests
from lxml import etree
import pandas as pd
import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36 Edg/101.0.1210.39"
}
comments = []
words = []
def regex_change(line):
# 前缀的正则
username_regex = re.compile(r"^\d+::")
# URL,为了防止对中文的过滤,所以使用[a-zA-Z0-9]而不是\w
url_regex = re.compile(r"""
(https?://)?
([a-zA-Z0-9]+)
(\.[a-zA-Z0-9]+)
(\.[a-zA-Z0-9]+)*
(/[a-zA-Z0-9]+)*
""", re.VERBOSE | re.IGNORECASE)
# 剔除日期
data_regex = re.compile(u""" #utf-8编码
年 |
月 |
日 |
(周一) |
(周二) |
(周三) |
(周四) |
(周五) |
(周六)
""", re.VERBOSE)
# 剔除所有数字
decimal_regex = re.compile(r"[^a-zA-Z]\d+")
# 剔除空格
space_regex = re.compile(r"\s+")
regEx = "[\n”“|,,;;''/?! 。的了是]" # 去除字符串中的换行符、中文冒号、|,需要去除什么字符就在里面写什么字符
line = re.sub(regEx, "", line)
line = username_regex.sub(r"", line)
line = url_regex.sub(r"", line)
line = data_regex.sub(r"", line)
line = decimal_regex.sub(r"", line)
line = space_regex.sub(r"", line)
return line
def getComments(url):
score = 0
resp = requests.get(url, headers=headers).text
html = etree.HTML(resp)
comment_list = html.xpath(".//div[@class='comment']")
for comment in comment_list:
status = ""
name = comment.xpath(".//span[@class='comment-info']/a/text()")[0] # 用户名
content = comment.xpath(".//p[@class='comment-content']/span[@class='short']/text()")[0] # 短评内容
content = str(content).strip()
word = jieba.cut(content, cut_all=False, HMM=False)
time = comment.xpath(".//span[@class='comment-info']/a/text()")[1] # 评论时间
mark = comment.xpath(".//span[@class='comment-info']/span/@title") # 评分
if len(mark) == 0:
score = 0
else:
for i in mark:
status = str(i)
if status == "力荐":
score = 5
elif status == "推荐":
score = 4
elif status == "还行":
score = 3
elif status == "较差":
score = 2
elif status == "很差":
score = 1
good = comment.xpath(".//span[@class='comment-vote']/span[@class='vote-count']/text()")[0] # 点赞数(有用数)
comments.append([str(name), content, str(time), score, int(good)])
for i in word:
if len(regex_change(i)) >= 2:
words.append(regex_change(i))
def getWordCloud(words):
# 生成词云
all_words = []
all_words += [word for word in words]
dict_words = dict(Counter(all_words))
bow_words = sorted(dict_words.items(), key=lambda d: d[1], reverse=True)
print("热词前10位:")
for i in range(10):
print(bow_words[i])
text = ' '.join(words)
w = WordCloud(background_color='white',
width=1000,
height=700,
font_path='simhei.ttf',
margin=10).generate(text)
plt.show()
plt.imshow(w)
w.to_file('wordcloud.png')
print("请选择以下选项:")
print(" 1.热门评论")
print(" 2.最新评论")
info = int(input())
print("前10位短评信息:")
title = ['用户名', '短评内容', '评论时间', '评分', '点赞数']
if info == 1:
comments = []
words = []
for i in range(0, 60, 20):
url = "https://book.douban.com/subject/10517238/comments/?start={}&limit=20&status=P&sort=new_score".format(
i) # 前3页短评信息(热门)
getComments(url)
df = pd.DataFrame(comments, columns=title)
print(df.head(10))
print("点赞数前10位的短评信息:")
df = df.sort_values(by='点赞数', ascending=False)
print(df.head(10))
getWordCloud(words)
elif info == 2:
comments = []
words = []
for i in range(0, 60, 20):
url = "https://book.douban.com/subject/10517238/comments/?start={}&limit=20&status=P&sort=time".format(
i) # 前3页短评信息(最新)
getComments(url)
df = pd.DataFrame(comments, columns=title)
print(df.head(10))
print("点赞数前10位的短评信息:")
df = df.sort_values(by='点赞数', ascending=False)
print(df.head(10))
getWordCloud(words)
请选择以下选项:
1.热门评论
2.最新评论
1
前10位短评信息:
Building prefix dict from the default dictionary ...
Loading model from cache C:\Users\20969\AppData\Local\Temp\jieba.cache
Loading model cost 0.420 seconds.
Prefix dict has been built successfully.
用户名 短评内容 ... 评分 点赞数
0 laura 像少平一样做一个对精神世界一丝不苟的人,像少安一样做一个对现实生活脚踏实地的人 ... 0 5217
1 威尼斯男人 不知是苏童还是余华说过,路遥的#《平凡的世界》#又臭又长,在最近电视剧热播的推动下,我化四天... ... 4 1063
2 yeat 这本书最大的的收获就是,可以知道农民的眼光是怎样看问题 ... 3 688
3 namik_ercan 《平凡的世界》体现了这一个时代的作品非常鲜明的语言特色,富有感情色彩的辞藻,直抒胸臆的表达形... ... 4 523
4 敦云™ 谢谢路遥,我几乎是迫不及待地把这这本书(三部)看完的,我很感动。回家尝试着用书中了解到的知识... ... 5 755
5 慕小雨 能把流水账写进茅盾文学奖,也是需要一定勇气和毅力的。全程主角光环开最大,最后发现光环挂不住了... ... 3 473
6 梵高的左耳 充斥了各种富贵女子爱上我的桥段,最后实在编不下去了只好把人家晓霞写死了。看着就来气。屌丝就会... ... 3 514
7 虾坨坨艺仔 惭愧,作为中文系学生今天才把这套著名的书通读完。语言的时代特色过于明显,因此文学性实在有限。... ... 3 291
8 曾于里 是一本好读、好看的小说,但就思想性、艺术性而言,与伟大作品差距明显 ... 3 294
9 麦快乐 最讨厌作者时不时跳出来,好像把读者当傻子一样用大白话解释本不用解释的小说情节。过誉了的一本书。 ... 2 276
[10 rows x 5 columns]
点赞数前10位的短评信息:
用户名 短评内容 ... 评分 点赞数
0 laura 像少平一样做一个对精神世界一丝不苟的人,像少安一样做一个对现实生活脚踏实地的人 ... 0 5217
1 威尼斯男人 不知是苏童还是余华说过,路遥的#《平凡的世界》#又臭又长,在最近电视剧热播的推动下,我化四天... ... 4 1063
4 敦云™ 谢谢路遥,我几乎是迫不及待地把这这本书(三部)看完的,我很感动。回家尝试着用书中了解到的知识... ... 5 755
2 yeat 这本书最大的的收获就是,可以知道农民的眼光是怎样看问题 ... 3 688
3 namik_ercan 《平凡的世界》体现了这一个时代的作品非常鲜明的语言特色,富有感情色彩的辞藻,直抒胸臆的表达形... ... 4 523
6 梵高的左耳 充斥了各种富贵女子爱上我的桥段,最后实在编不下去了只好把人家晓霞写死了。看着就来气。屌丝就会... ... 3 514
5 慕小雨 能把流水账写进茅盾文学奖,也是需要一定勇气和毅力的。全程主角光环开最大,最后发现光环挂不住了... ... 3 473
8 曾于里 是一本好读、好看的小说,但就思想性、艺术性而言,与伟大作品差距明显 ... 3 294
7 虾坨坨艺仔 惭愧,作为中文系学生今天才把这套著名的书通读完。语言的时代特色过于明显,因此文学性实在有限。... ... 3 291
10 喂饭 写法和技巧不多不少match cctv国产剧水平,把偏见当公义,把愚钝当朴实,把保守主义当“... ... 2 284
[10 rows x 5 columns]
热词前10位:
('时代', 14)
('作者', 14)
('平凡', 12)
('一个', 10)
('没有', 10)
('路遥', 9)
('故事', 9)
('小说', 8)
('生活', 8)
('作品', 8)
请选择以下选项:
1.热门评论
2.最新评论
2
前10位短评信息:
Building prefix dict from the default dictionary ...
Loading model from cache C:\Users\20969\AppData\Local\Temp\jieba.cache
Loading model cost 0.414 seconds.
Prefix dict has been built successfully.
用户名 短评内容 ... 评分 点赞数
0 Kazzy 高开低走,我只能说第一部第一章唬住我了,后面都是啥玩意啊 ... 2 0
1 不会遗憾就OK了 史诗级著作 ... 5 0
2 江博格 平凡的世界分3步曲,我就看了第一部故事,其中李向前是最令我悲悯的人,她的爱人润叶不爱他,确是... ... 5 0
3 方便查到的昵称 24.05.29 第一部 每个角色都正直勤劳 ... 5 0
4 Emanuel L 看到 晓霞被洪水冲走的时候 眼泪汪汪 ... 5 0
5 豆友wZu3WWDhrs 人生必读 ... 5 0
6 momo 鬼使神差,耐着性子看完了。结论:恭喜作者的运气,佩服茅奖的勇气 ... 0 1
7 老滑稽 平凡的我们,也将回到平凡的世界,生活中充满孩子哭声柴米和油盐,曾和你走过麦迪逊花园,任意门外... ... 4 0
8 白昼梦游指南. 没注意,看的普及本,以后再看原著吧! ... 4 0
9 neil 不同年龄段看书的感悟各不相同。多加勉励自己,少刷手机,多看书,摆脱内心的浮躁 ... 5 0
[10 rows x 5 columns]
点赞数前10位的短评信息:
用户名 短评内容 ... 评分 点赞数
29 矿泉水 补卡,2016年读完,这是我心中的神,中文写作里最好没有之一。 ... 5 1
47 年糕公主 (近两年阅读的第一本大部头,在423阅读挑战的督促下完成)很喜欢第二卷,每个人都找到了自己的... ... 5 1
6 momo 鬼使神差,耐着性子看完了。结论:恭喜作者的运气,佩服茅奖的勇气 ... 0 1
36 吃啥不吃大闸蟹 写得真好啊,平实语言见功力。感觉未完待续,折回去看了眼,88年完稿,92年离世…可惜 ... 5 1
49 YBING 很遗憾,并没有感受到这本小说的伟大,反而感觉有些情节和人物关系的转变不太合理或不太可能…… ... 3 1
0 Kazzy 高开低走,我只能说第一部第一章唬住我了,后面都是啥玩意啊 ... 2 0
39 豆友cKDVRs7Iko 用了两个月断断续续的读完了三部,1975到1985十年的跨越,十年的变迁,围绕少平,少安的亲... ... 5 0
42 果子 我们就一天天长大;被一个个黄土地情歌感动;生活的诗情永远充满青年的胸膛;顽强的生命力;对生命... ... 5 0
41 液断中 《平凡的世界》是一部描绘中国农村生活的现实主义小说,它以孙少安和孙少平两兄弟为主线,讲述了他... ... 5 0
40 彩虹 从苦难里站起来的人再回头救赎苦难,歌颂苦难 ... 4 0
[10 rows x 5 columns]
热词前10位:
('平凡', 33)
('生活', 28)
('世界', 17)
('我们', 16)
('自己', 13)
('一个', 13)
('故事', 12)
('没有', 11)
('时代', 11)
('那个', 9)

浙公网安备 33010602011771号