Python爬取微博话题博文,保存为TXT格式

利用Python,爬取微博上有关某个话题的博文,例如#凉拌黄瓜#,最后将每一条博文内容的结果单独保存为一个txt格式。

回答之前请确保能跑起来,不要给我gpt写的死代码。

来了

img

from selenium import webdriver
import time
import os

# 初始化 Chrome 浏览器
driver = webdriver.Chrome()

# 打开微博页面,此处以某个话题页为例
weibo_url = "https://s.weibo.com/weibo?q=%2305%E5%90%8E%E5%B7%B2%E7%BB%8F%E8%BF%9B%E5%8C%96%E5%88%B0%E8%BF%99%E7%A7%8D%E7%A8%8B%E5%BA%A6%E4%BA%86%E5%90%97%23"
driver.get(weibo_url)

# 等待页面加载完成
time.sleep(5)

# 解析页面内容
page_source = driver.page_source

# 使用 Beautiful Soup 解析页面内容
from bs4 import BeautifulSoup
soup = BeautifulSoup(page_source, "html.parser")

# 查找博文内容
posts = soup.find_all("p", class_="txt")

# 设置保存目录
save_dir = "/Users/xx/Downloads/weibo_results/"

# 创建保存目录
if not os.path.exists(save_dir):
    os.makedirs(save_dir)

# 逐条保存博文内容为 txt 文件
for i, post in enumerate(posts):
    post_text = post.get_text(strip=True)
    file_path = os.path.join(save_dir, f"weibo_{i + 1}.txt")

    with open(file_path, "w", encoding="utf-8") as file:
        file.write(post_text)

    print(f"保存第{i + 1}条微博至 {file_path}")

# 关闭浏览器
driver.quit()

print("爬取和保存完成!")


【以下回答由 GPT 生成】

答案:

我可以给你一个大体的解决方案,但请注意,由于微博的官方限制,直接爬取微博数据可能违规,可能会导致你的账号被封禁。所以,在尝试爬取微博数据之前,请确保你已经阅读并理解相关的法律法规,并且尊重微博的使用协议。

下面是一个基本的爬取微博博文的思路和代码示例:

  1. 安装所需的依赖库: pip install requests BeautifulSoup

  2. 导入所需的模块: python import requests from bs4 import BeautifulSoup

  3. 使用requests模块发送HTTP请求获取特定话题的页面内容: python url = 'https://s.weibo.com/weibo?q=' + topic # 替换topic为你要搜索的特定话题 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} response = requests.get(url, headers=headers)

  4. 使用BeautifulSoup解析页面内容,提取每条博文的信息: python soup = BeautifulSoup(response.text, 'html.parser') # 找到每条微博所在的元素 weibo_elements = soup.find_all('div', class_='card-wrap') for element in weibo_elements: # 解析每条微博的相关信息 # 标题 title = element.find('p', class_='txt').text.strip() # 内容 content = element.find('p', class_='txt').text.strip() # 用户名 username = element.find('a', class_='name').text.strip() # 时间 time = element.find('p', class_='from').find_all('a')[0].text.strip() # 保存为txt文件 with open(username + '_' + time + '.txt', 'w', encoding='utf-8') as file: file.write(content)

以上是一个基本的爬取微博博文并保存为txt文件的思路和代码示例。请注意,由于微博页面结构可能随时变化,所以代码可能需要适应微博页面的改动。

再次强调,请确保你已经了解相关法律法规和微博的使用协议,并遵守他们。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

import os
import requests
from bs4 import BeautifulSoup

# 话题关键词
topic = "凉拌黄瓜"

# 创建文件夹来保存结果
if not os.path.exists(topic):
    os.makedirs(topic)

# 构造爬取的 URL
base_url = f"https://s.weibo.com/weibo?q=%23{topic}%23"
headers = {
    "User-Agent": "Your User-Agent String",  # 替换为您的 User-Agent
}

# 发起请求
response = requests.get(base_url, headers=headers)

if response.status_code == 200:
    # 使用 BeautifulSoup 解析页面内容
    soup = BeautifulSoup(response.content, "html.parser")
    
    # 定位博文内容
    posts = soup.find_all("p", class_="txt")
    
    # 逐条保存博文内容
    for i, post in enumerate(posts, start=1):
        post_text = post.get_text()
        with open(f"{topic}/post_{i}.txt", "w", encoding="utf-8") as f:
            f.write(post_text)
        print(f"博文 {i} 已保存")
else:
    print("请求失败,状态码:", response.status_code)


import os
import requests
from bs4 import BeautifulSoup
# 话题关键词
topic = "凉拌黄瓜"
# 创建文件夹来保存结果
if not os.path.exists(topic):
    os.makedirs(topic)
# 构造爬取的 URL
base_url = f"https://s.weibo.com/weibo?q=%23{topic}%23"
headers = {
    "User-Agent": "Your User-Agent String",  # 替换为您的 User-Agent
}
# 发起请求
response = requests.get(base_url, headers=headers)
if response.status_code == 200:
    # 使用 BeautifulSoup 解析页面内容
    soup = BeautifulSoup(response.content, "html.parser")
    # 定位博文内容
    posts = soup.find_all("p", class_="txt")
    # 逐条保存博文内容
    for i, post in enumerate(posts, start=1):
        post_text = post.get_text()
        with open(f"{topic}/post_{i}.txt", "w", encoding="utf-8") as f:
            f.write(post_text)
        print(f"博文 {i} 已保存")
else:
    print("请求失败,状态码:", response.status_code)


```