iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python爬取热搜制作词云
  • 679
分享到

python爬取热搜制作词云

2024-04-02 19:04:59 679人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

环境:win10,64位,Mysql5.7数据库,python3.9.7,ancod 逻辑流程: 1、首先爬取百度热搜,至少间隔1小时2、存入文件,避免重复请求,如果本1小时有了不再

环境:win10,64位,Mysql5.7数据库python3.9.7,ancod

逻辑流程:

  • 1、首先爬取百度热搜,至少间隔1小时
  • 2、存入文件,避免重复请求,如果本1小时有了不再请求
  • 3、存入数据库,供词云包使用
  • 1、爬取热搜,首先拿到url,使用的包urllib,有教程urllib2python2的。

'''读取页面'''
def readhtml(self,catchUrl):
    catchUrl=self.catchUrl if not catchUrl else catchUrl
    response=urllib.request.urlopen(catchUrl)
    text=response.read().decode(self.bmcode)
    return text


这里在本类定义了几个属性,上述self的就是,这不是重点,继续,上述使用了三目运算符


'''生成时间'''
    def createTime(self):
        # 格式化成2016-03-20 11:45:39形式
        return time.strftime("%Y%m%d%H", time.localtime())
    '''写入文件'''
    def write2file(self,text):
        fileName=self.writePosition+self.createTime()+'.txt'
        self.fileName=fileName
        print(fileName)
        #判断路径,不存在生成
        if not os.path.exists(self.writePosition):
            os.mkdir(self.writePosition )
        if os.path.exists(fileName):
            uuid_tools().printlog('已经存在:{}'.fORMat(fileName))
            return self.fileName
        mode='a' if os.path.exists(fileName) else 'w'
 
        with open(fileName,mode,encoding=self.bmcode) as f:
            f.write(text)
        print("写入{} 完成".format(fileName))
        return self.fileName


这里每个小时生成一个文件名称,避免了重复,如果这一小时里已经抓取过了,那么不再抓取了。

这里使用了日志(需导入日志包import logging):


    '''打印日志'''
    def printlog(self,loginfo):
        logging.basicConfig(level=logging.INFO)
        logging.info(loginfo)


获取到内容后,这里需要去掉<div>xxx</div>这个东西,还有个查看更多


'''去掉标签'''
    def removeBq(self,content):
        pat=re.compile('>(.*?)<')
        str=''.join(pat.findall(content))
        str=str.replace(' 查看更多&gt; ','')
        return str
    '''输出内容'''
    def printContent(self, o,class_name):
        print(self.removeBq(str(o.find(class_=class_name))))


这里是beautifulsoup分析html格式的内容:


'''测试获取某个片段'''
    def readFilePd(self,fileName):
        #fileName='d:\\bdrs\\2021122010.txt'
        jt=open(fileName,'r',encoding=self.bmcode)
        try:
            content=jt.read()
            soup=BeautifulSoup(content,"html.parser")
            rs=RsBean()
            for k in soup.find_all('div',class_=rs.alldiv):
                print( str(k))
                # self.printContent(k,rs.sx)
                # self.printContent(k,rs.bt)
                # self.printContent(k,rs.ms)
                # self.printContent(k,rs.rszs)
        except  Exception as e:
            print('error:'+str(e))


最主要的是这一句:soup.find_all('div',class_='xxx')尤其这个横杠,是该方法参数,代表标签的class名称。

最后插入数据库,


'''打开连接'''
    def open(self):
        self.db=pymysql.connect(host=self.host,port=3306,user=self.user,passwd=self.passwd,db=self.database)
        #创建游标
        self.cursor=self.db.cursor()
        #print("打开连接成功")
    #关闭
    def close(self):
        self.cursor.close()
        self.db.close()
        #print("close连接成功")
def execute(self,sql,list=[]):
        try:
            self.open()
            self.cursor.execute(sql,list)
            self.db.commit()
            print("execute successfully!")
        except Exception as e:
            self.db.rollback()
            print("Execute failure!",str(e))
        self.close()


封装的代码,后边这样使用:


'''读取文件'''
    def readFile(self,fileName):
        #fileName='d:\\bdrs\\2021122010.txt'
        jt=open(fileName,'r',encoding=self.bmcode)
        try:
            content=jt.read()
            soup=BeautifulSoup(content,"html.parser")
            rs=RsBean()
            daoOper=OperateRsDao()
            rs_shijian=self.cutfilename(fileName)
            #先清空
            self.clearBefore(daoOper,rs_shijian)
            #读取文件
            for k in soup.find_all('div',class_=rs.alldiv):
                #插入数据
                rs.rs_shijian=rs_shijian
                self.insertData(daoOper,k,rs)
        except  Exception as e:
            print('error:'+str(e))


最后词云显示:


if __name__ == '__main__':
    a=db_connect()
    sql='select id,shun_xu,biao_ti,miao_shu,reshou_zhishu,insert_time,rs_shijian from bdrs_one order by rs_shijian desc,shun_xu asc '
    result=a.select(sql)
    jieguo=''
    for m in result:
        print(m)
        jieguo+=m[2]
    #根据title做词云
    CiYun().showImage(jieguo)


效果:

 可以看出最大的瓜是啥。

到此这篇关于Python爬取百度热搜制作词云的文章就介绍到这了,更多相关python爬取热搜制作词云内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: python爬取热搜制作词云

本文链接: https://www.lsjlt.com/news/160648.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作