试着用python做一个贴吧热搜关键词的分析。
第一步先用python的selenium去读取热搜(selenium并不是一个很好的爬虫选择,效率很低,但是简单好用)
下面简单的代码
下面的读出来的内容
读出来后我们试着把它放在数据库里,打开MySQL,登录。
然后创建一个数据库,就简简单单三列就可以,id,内容,日期。
接下来用MySQL试试手动添加数据
成功了,好了我们进行下一步,使用pymysql试试插入数据
把要输入的数据做一些调整,日期要当天的,内容改为要输入的。
接下来合起来运行一下,数据库查看一下结果
不过我想到了一个问题,要是多运行几次不就会导致重复内容吗?设计的时候忘了,给内容添加一个唯一的约束吧。
在输入的时候也查一下内容有没有重复的有的话就不写入了。
这样我们就可以得到热搜的内容并且保存在mysql里面。
在数据库里我们就可以做其他的操作了,比如用jieba断句,看看有那些关键词,好吧有点乱。
我们可以用其他方法来看一下关键词有有什么,用wrodcloud如下
这样看起来就好多了,不过这是这一天的内容,要是能收集一年的热搜内容,我觉得关键词一定的“如何”“评价”抗压背锅那群比是真的tm能水。代码如下两部分
from selenium import webdriver
from selenium.webdriver.common.by import By
import pymysql
import time
coon=pymysql.connect(
host='127.0.0.1',
user='root',
password='123456',
database='teiba',
charset='utf8',
port=3306
)
sql=" insert into reshou (neirong ,time ) values (%s,%s);"
sql1="select neirong from reshou where neirong regexp %s;"
cursor=coon.cursor()
driver= webdriver.Chrome()
driver.implicitly_wait(10)
driver.get('https://tieba.baidu.com/hottopic/browse/topicList?res_type=1')
a=driver.find_elements(By.CLASS_NAME,'topic-text')
for i in a:
val1=i.text
cursor.execute(sql1, val1)
result=cursor.fetchall()
if len(result)==0:
val = []
time1 = time.strftime('%Y-%m-%d')
val.append(i.text)
val.append(time1)
cursor.execute(sql,val)
coon.commit()
driver.quit()
coon.close()
import pymysql
import time
import jieba
import wordcloud
coon=pymysql.connect(
host='127.0.0.1',
user='root',
password='123456',
database='teiba',
charset='utf8',
port=3306
)
cursor=coon.cursor()
sql="select neirong from reshou ;"
cursor.execute(sql)
re=cursor.fetchall()
a=[]
string=""
for i in re:
i=str(i)
i=i.lstrip("('")
i=i.rstrip(",')")
a=jieba.cut(i)
for j in a:
string=string+','+j
w=wordcloud.WordCloud(max_words=500,max_font_size=50,font_path="C:\Windows\Fonts\simhei.ttf")
w.generate(string)
w.to_file('贴吧热搜关键词.jpg')
print(string)
coon.commit()
coon.close()