python 爬取微博实时热搜,并存入数据库实例

 
 

刚学python没几天,打算用paython爬去微博热搜数据试验一下,但是发现微博热搜是动态数据,网页源码并不能直接获取想要的数据,network里也并不能找到相关内容,这时重新查看网页源码,发现有类似中文编码的源码,数一下正好50个,不出意外这个就是我们需要的内容,但是这一串字符加了干扰,直接把中间所有的数字25删除后解析成中文发现就是微博热搜的主题

以下是完整代码

#!python3
#encoding=utf-8
import urllib,pymysql,requests,re
#配置数据库
config = {
          'host':'127.0.0.1',
          'port':3306,
          'user':'root',
          'password':'123456',
          'db':'weibo',
          'charset':'utf8',
          }
#链接数据库
conn=pymysql.connect(**config)
cursor=conn.cursor()
#获取热搜源码
weiboHotFile=requests.get('http://s.weibo.com/top/summary')
weiboHotHtml=weiboHotFile.text
#正则表达式匹配URL ,找到title
hotKey=re.compile(r'td class=\\"td_05\\"><a href=\\"\\/weibo\\/(.*?)&Refer=top\\"')
hotKeyListBe=hotKey.findall(weiboHotHtml)
rank=1
#遍历获取的title 列表
for title in hotKeyListBe:
    #去除干扰数字
    title=title.replace('25','')
    url='http://s.weibo.com/weibo/'+title
    title=urllib.parse.unquote(title)
    print(str(rank)+' '+title+' '+url+'\n')
    #执行数据语句
    sql='insert into hotsearch (rank,daydate,mindate,title,url) values (%s,curdate(),curtime(),%s,%s)'
    cursor.execute(sql,(rank,title,url))
    rank+=1
    conn.commit()
cursor.close()
conn.close()

创建一个bat 文件,运行python脚本


猜你喜欢

转载自blog.csdn.net/weixin_41407399/article/details/79775900