用Python爬取微博评论

发布时间:2023-05-10

介绍

微博是一个社交媒体平台,允许用户在其平台上发布信息、分享照片和视频。这个平台也是一个信息获取来源,如其用户的评论和转发。在本文中,我们将介绍如何使用 Python 代码从微博上爬取评论。

Python根据关键字爬取微博

许多人使用微博来查找有关特定关键字的信息。我们可以通过 Python 代码轻松地从微博上爬取这些信息。以下是 Python 爬取微博的示例代码:

    # 引入所需的库
    import requests 
    from bs4 import BeautifulSoup
    url = 'https://s.weibo.com/weibo?q=Python&Refer=STopic_box'
    res = requests.get(url)
    html = res.text
    soup = BeautifulSoup(html,'html.parser')
    content_lis = soup.find_all('p',class_='txt')
    for content in content_lis:
        print(content.text)

上面的代码中,我们引入了 requests 库和 BeautifulSoup 库。使用 requests 库获取关于 Python 的微博网页内容,用 BeautifulSoup 库将网站的 HTML 解析为可供操作的格式。 最后,我们从页面中找到类名为 "txt" 的段落标签,打印出其中文本内容。

Python爬取微博评论代码

在微博上,我们还可以获取某条微博的评论。因此,想要从某条微博上获取评论内容,需要先获取该微博的 URL。下面的代码给出了如何从一个特定用户名和某条特定微博的 ID 来获取评论内容。

    # 引入所需的库
    import requests 
    from bs4 import BeautifulSoup
    user_name = 'user_name'
    weibo_id = 'id'
    url = 'https://weibo.cn/comment/'+weibo_id+'?uid='+user_name+'&page=1'
    res = requests.get(url)
    html = res.text
    soup = BeautifulSoup(html,'html.parser')
    content_lis = soup.find_all('span',class_='ctt')
    for content in content_lis:
        print(content.text)

上面 “user_name” 必须替换为所需的用户名,"id" 必须被替换为所需的微博 ID 值。我们使用 requests 库。通过上面获取的 URL,获取关于评论微博页面内容,然后将 HTML 解析成 BeautifulSoup 对象。 最后,我们从批准的 comment 节点中找到类名为 “ctt” 的段落标签,打印评论。

Python爬取微博数据

我们可以使用 Python 获取有关特定用户在微博上的所有微博和评论。使用 Python 代码获取微博信息,可能是在爬取时被微博相关限制最为困难的任务。可以使用微博开放 API(Application Programming Interface)来获取这些信息。另一种方式是通过网站获取,并遵守关于获取数据的限制。

Python爬取微博热搜榜

微博热搜榜是获得热点新闻和事件的一个常用来源,这里将介绍使用 Python 来爬取微博热搜榜。以下是 Python 爬取微博热搜榜的示例代码。

    # 引入所需的库
    import requests
    from bs4 import BeautifulSoup
    url = 'https://s.weibo.com/top/summary?cate=realtimehot'
    res = requests.get(url)
    html = res.text
    soup = BeautifulSoup(html,'html.parser')
    content_lis = soup.find_all('td',class_='td-02')
    for content in content_lis:
        print(content.text)

我们首先将页面 HTML 网页下载到本地,然后使用 BeautifulSoup 库进行操作。 找到页面中类名为 “td-02” 的内容,就是热门话题的内容。

用Python爬取微博热搜

我们还可以爬取某个地域内微博用户关心的热点话题。此处用 Python 代码实现这个功能。以下是 Python 爬取微博热搜的示例代码。

    # 引入所需的库
    import requests
    from bs4 import BeautifulSoup
    city = '北京'
    url = 'https://s.weibo.com/top/summary?cate=realtimehot&city='+city
    res = requests.get(url)
    html = res.text
    soup = BeautifulSoup(html,'html.parser')
    content_lis = soup.find_all('td',class_='td-02')
    for content in content_lis:
        print(content.text)

和上述代码的差别仅仅在于URL,这个URL设置了一个地域,并返回了该地域的热门话题。

Python爬取某人所有微博

如果我们想要获取某个微博用户发布的所有的微博并保存到本地,可以使用以下的代码。下面示例代码中的用户名是 "user_name",文件名是 "user_weibo.txt"。代码中使用了 requests 库中的 get 函数发起 GET 请求,用于访问该用户的主页。然后,该请求响应的 HTML 被解析为一个 Beautiful Soup 对象,以便提取所需信息。

    # 引入所需的库
    import requests
    from bs4 import BeautifulSoup
    headers ={
        'USER-Agent':'Mozilla/5.0(X11;Linuxx86_64;rv:60.0) Gecko/20100101Firefox/60.03.0esr'
    }
    name = 'user_name'
    url = 'https://weibo.cn/'+name+'/profile?filter=1&page=1'
    r = requests.get(url,headers=headers)
    html = r.text
    soup = BeautifulSoup(html,'html.parser')
    page_list = soup.find_all('div',class_='pa')
    for index in range(0,len(page_list)):
        url = 'https://weibo.cn/'+name+'/profile?filter=1&page='+str(index+1)
        r = requests.get(url,headers=headers)
        html = r.text
        soup = BeautifulSoup(html,'html.parser')
        page_info = soup.find_all('span',class_='ctt')
        for page in page_info:
            print(page.text)
            path = 'user_weibo.txt'
            with open(path,'a') as liver_pool:
                liver_pool.write(page.text)

当结果被解析好后,我们可以看到 Beautiful Soup 对象中有数个 "div" 元素,每一个都代表一条微博。我们用 Python 代码来找到并获取这些元素,将其存储到一个列表中。之后释放请求,(循环运行)获取每一页的数据,将其存储在对应的 .txt 文件中,其中每当一个新的微博被找到时,相应的文本就会被写入文件。

Python爬取微博内容和评论

下面,给出了一个完整的示例代码,可以同时获取某个用户在微博上的所有微博和它们的评论,并将数据保存到同一个文件中。

    # 引入所需的库
    import requests
    from bs4 import BeautifulSoup
    headers ={
        'USER-Agent':'Mozilla/5.0(X11;Linuxx86_64;rv:60.0) Gecko/20100101Firefox/60.03.0esr'
    }
    name = 'user_name'
    url = 'https://weibo.cn/'+name+'/profile?filter=1&page=1'
    r = requests.get(url,headers=headers)
    html = r.text
    soup = BeautifulSoup(html,'html.parser')
    # 从网页中获取微博链接并存储到列表中
    find_class = soup.find_all('div',class_='c',id=True)
    find_list = []
    for ident in find_class:
        find_list.append('https://weibo.cn/comment/'+ident['id'][2:]+'?uid='+name+'&page=1')
    data_set = []
    # 获取每个微博的评论并将其存储在列表中
    for url in find_list:
        try:
            r = requests.get(url,headers=headers)
            html = r.text
            soup = BeautifulSoup(html,'html.parser')
            info = soup.find_all('span',class_='ctt')
            for i in info:
                data_set.append(i.text)
        except:
            continue
    # 获取每一页的微博并将其存储在列表中
    page_list = soup.find_all('div',class_='pa')
    for index in range(0,len(page_list)):
        url = 'https://weibo.cn/'+name+'/profile?filter=1&page='+str(index+1)
        try:
            r = requests.get(url,headers=headers)
            html = r.text
            soup = BeautifulSoup(html,'html.parser')
            info = soup.find_all('span',class_='ctt')
            for i in info:
                data_set.append(i.text)
        except:
            continue
    # 存储至文件
    path = 'user.txt'
    with open(path,'w') as liver_pool:
        for ent in data_set:
            liver_pool.write(ent+'\n')
    print('Data has been written to "user.txt"')

首先,通过 requests 库的 get() 方法请求出特定用户的主页内容,将 html 内容作为参数传递给 BeautifulSoup() 方法进行解析, 然后我们可以找到每个微博的评论,将它们存储到一个列表中。之后我们获取此用户在每一页的微博,并存储到同一个文本文件中。在示例代码中,文件名为 “user.txt”。