用Python爬取微博热搜数据

废话少说,直接上代码,然后再详细介绍构造过程。

代码

import urllib.request
import re
import pandas as pd
import time
import random

def getdata():
    url='https://s.weibo.com/top/summary?cate=realtimehot'
    req=urllib.request.Request(url)
    req.add_header('User-Agent',' Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36')
    data=urllib.request.urlopen(req).read().decode('utf-8')
    str1=str(data)
    pat1='">(.*?)</a>'
    pat2='<span>(.*?)</span>'
    result1=re.compile(pat1).findall(str1)
    result2=re.compile(pat2).findall(str1)
    a=result1[4:55]
    return a,result2

if __name__ == '__main__':
    for i in range(0,15):
        name=time.strftime("%Y-%m-%d-%H-%M-%S",time.localtime())
        data=getdata()
        print('置顶榜为:',data[0][0])
        hot=data[0][1:56]
        dataframe = pd.DataFrame({'热搜榜': hot, '热点数:': data[1]})
        dataframe.to_csv(name+".csv", index=False, sep=',', encoding="utf_8_sig", mode="a+")
        time.sleep(random.randint(1,30))

在这里插入图片描述
在这里插入图片描述

Step1:确定网址

数据爬取的是微博热搜榜,解析网页信息并解码。

代码

req=urllib.request.Request(url)
data=urllib.request.urlopen(req).read().decode('utf-8')

在这里插入图片描述

Step2:反爬机制

有些网站需要定义反爬机制。

代码

req.add_header('User-Agent',' Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36')

有关User-Agent的知识可参考Python爬虫:将User-Agent添加进网页请求头

Step3:正则式匹配

打开源数据网页,查看源代码,确定爬取数据的位置。见下图:
在这里插入图片描述

则爬取的位置是:

  <a href="/weibo?q=%E5%BE%97%E7%89%A9%E5%B4%A9%E4%BA%86&Refer=top" target="_blank">得物崩了</a>
  <a href="/weibo?q=%E8%89%BE%E6%AF%94%E5%B0%8F%E5%8F%B7&Refer=top" target="_blank">艾比小号</a>
  <a href="/weibo?q=%23%E4%B8%80%E8%B5%B7%E8%8B%97%E8%8B%97%E8%8B%97%E8%8B%97%E8%8B%97%23&Refer=top" target="_blank">一起苗苗苗苗苗</a>
  

  <span>1427950</span>
  <span>1373588</span>
 <span>1331551</span>
  

确定正则匹配式:

  pat1='">(.*?)</a>'
  pat2='<span>(.*?)</span>'

Step4:将爬取数据写入表格并保存

首先导入pandas库。

import pandas as pd

写入表格并保存:

dataframe = pd.DataFrame({'热搜榜': hot, '热点数:': data[1]})
dataframe.to_csv(name+".csv", index=False, sep=',', encoding="utf_8_sig", mode="a+")

至此所有的步骤都已完成。
在这里插入图片描述

  • 3
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 我可以提供一些有关用Python微博的建议:1.使用Python虫库来微博;2.使用requests库来获微博数据;3.使用BeautifulSoup库来解析到的微博数据。 ### 回答2: 要用Python微博,可以使用第三方库beautifulsoup和requests。首先,需要安装这两个库,并导入它们。 ``` pip install beautifulsoup4 pip install requests ``` 然后,导入需要的模块: ```python import requests from bs4 import BeautifulSoup ``` 接下来,使用requests库发送HTTP请求,获微博的网页内容: ```python url = "https://s.weibo.com/top/summary?cate=realtimehot" response = requests.get(url) ``` 通过调用response对象的text属性,可以获网页内容的字符串形式。然后,使用beautifulsoup库进行解析,以便从页面中提榜的内容。 ```python soup = BeautifulSoup(response.text, "html.parser") ``` 可以使用beautifulsoup的find()或find_all()方法根据标签名或CSS选择器来查找所需的元素。例如,可以通过以下代码获榜的所有内容: ```python hot_topics = soup.find_all("td", class_="td-02") ``` 接下来,可以通过循环遍历hot_topics列表,提出每个的文本内容,并将其打印出来: ```python for topic in hot_topics: print(topic.get_text()) ``` 这样就可以通过Python微博榜的内容了。需要注意的是,由于网站可能存在反机制,可能需要使用一些虫策略(如设置User-Agent、使用代理等)来避免被屏蔽。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值