使用selenium库模拟浏览器登陆,由于selenium不支持phantomJS,所以本文使用google浏览器。首先用anaconda安装好selenium库,然后下载chromedriver复制到python路径中。打开一个有空间访问权限的好友空间,找到其说说页,使用webdrive请求网页。
driver = webdriver.Chrome()
driver.get('https://user.qzone.qq.com/qq号码/311')#qq号码为自己的qq号
运行后网页会跳到一个认证页面,需要输入账号和密码
driver.switch_to_frame('login_frame') driver.find_element_by_id('switcher_plogin').click() driver.find_element_by_id('u').clear() driver.find_element_by_id('u').send_keys('账号') driver.find_element_by_id('p').clear() driver.find_element_by_id('p').send_keys('密码') driver.find_element_by_id('login_button').click() time.sleep(3)
之后页面会跳转到好友的qq空间说说页面,使用select选择器提取说说内容,在结尾加入$符号,方便之后的分词,并保存在shuoshuo.txt文件中
while next_page: try: contents = driver.find_elements_by_css_selector('.content') for content in contents: print(content.text) with open('shuoshuo.txt','a+') as f: f.write(content.text) f.write('$') next_page = driver.find_element_by_link_text(u'下一页') page = page + 1 print(u'正在抓取第{}页面内容······',format(page)) next_page.click() time.sleep(3)
之后使用jieba库对好友说说进行分词,首先打开文件,然后提取每行数据
file = open('shuoshuo.txt','r') content = file.readlines() word_dict = {} s = '' for ct in content: list1 = ct.split('$') for cont in list1: s=s+cont+','
然后jieba进行关键词提取,并统计权重,然后保存下来
cut1 = jieba.analyse.extract_tags(s,topK = 2000,withWeight=True)
with open('shuoshuo_keyword.txt','a+') as f1: for item in cut1: f1.write(item[0]+' '+str(item[1])+ '\n')
之后使用wordcloud进行关键词的可视化处理
file = open('e:\project\pachong\shuoshuo_keyword.txt','r') for line in file.readlines(): lis1.append(line.split()[0]) lis2.append(float(line.split()[1])) text = dict(zip(lis1,lis2))
back_coloring = imread(r'背景图片.png') wc = WordCloud( font_path=r'c:\Windows\Fonts\STZHONGS.TTF',#设置字体 background_color="gray", #背景颜色 max_words=300,# 词云显示的最大词数 mask=back_coloring,#设置背景图片 max_font_size=100, # min_font_size=10, random_state=50, scale=3 ) wc.fit_words(text) image_colors = ImageColorGenerator(back_coloring) plt.figure() plt.imshow(wc.recolor(color_func=image_colors)) plt.axis("off") plt.show() wc.to_file("词云.png")
最后为生成的结果展示:
![](https://i-blog.csdnimg.cn/blog_migrate/77788ce6b89c151c5c3ce68e119affc6.png)
![](https://i-blog.csdnimg.cn/blog_migrate/c930c135297adc7198d5fa261d1ad040.png)