python爬取热搜制作词云

 更新时间:2022年01月25日 10:54:46   作者:Dead_Cicle  
这篇文章主要介绍了python爬取百度热搜制作词云,首先爬取百度热搜,至少间隔1小时,存入文件,避免重复请求,如果本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爬取热搜制作词云内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python在报表自动化的优势及实现流程

    Python在报表自动化的优势及实现流程

    本文利用Python实现报表自动化,通过介绍环境设置、数据收集和准备、报表生成以及自动化流程,展示Python的灵活性和丰富的生态系统在报表自动化中的卓越表现,从设置虚拟环境到使用Pandas和Matplotlib处理数据,到借助APScheduler实现定期自动化,每个步骤都得到详尽阐述
    2023-12-12
  • Python中的urllib模块使用详解

    Python中的urllib模块使用详解

    这篇文章主要介绍了Python中的urllib模块使用详解,是Python入门学习中的基础知识,需要的朋友可以参考下
    2015-07-07
  • python利用dlib获取人脸的68个landmark

    python利用dlib获取人脸的68个landmark

    这篇文章主要介绍了python利用dlib获取人脸的68个landmark,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-11-11
  • 利用Python实现Windows下的鼠标键盘模拟的实例代码

    利用Python实现Windows下的鼠标键盘模拟的实例代码

    本篇文章主要介绍了利用Python实现Windows下的鼠标键盘模拟的实例代码,具有一定的参考价值,有兴趣的可以了解一下
    2017-07-07
  • python基础教程之五种数据类型详解

    python基础教程之五种数据类型详解

    这篇文章主要介绍了python基础教程之五种数据类型详解的相关资料,这里对Python 的数据类型进行了详细介绍,需要的朋友可以参考下
    2017-01-01
  • 浅谈numpy数组的几种排序方式

    浅谈numpy数组的几种排序方式

    这篇文章主要介绍了浅谈numpy数组的几种排序方式,涉及对numpy的简单介绍和创建数组的方式,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • python访问sqlserver示例

    python访问sqlserver示例

    这篇文章主要介绍了python访问sqlserver示例,需要的朋友可以参考下
    2014-02-02
  • python爬虫线程池案例详解(梨视频短视频爬取)

    python爬虫线程池案例详解(梨视频短视频爬取)

    这篇文章主要介绍了python爬虫线程池案例详解(梨视频短视频爬取),本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-02-02
  • Django 表单模型选择框如何使用分组

    Django 表单模型选择框如何使用分组

    这篇文章主要介绍了Django 表单模型选择框如何使用分组,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-05-05
  • 几个适合python初学者的简单小程序,看完受益匪浅!(推荐)

    几个适合python初学者的简单小程序,看完受益匪浅!(推荐)

    这篇文章主要介绍了几个适合python初学者的简单小程序,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04

最新评论