You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R的rvest包爬取Polititweet上马斯克的已删推文文本并自动分页?

如何用R爬取Polititweet上埃隆·马斯克的所有已删推文文本

1. 自动获取总页数

先从第一页的分页信息中提取总页数,避免手动指定页数的局限性:

library(rvest)
library(stringr)

# 定义URL模板,%d用于后续填充页码
base_url <- "https://polititweet.org/tweets?page=%d&deleted=True&account=44196397&search="

# 加载第一页内容
first_page <- read_html(sprintf(base_url, 1))

# 提取分页文本(例如"Page 1 of 9")并解析总页数
pagination_info <- html_text(html_nodes(first_page, ".pagination-info"))
total_pages <- as.integer(str_extract(pagination_info, "\\d+$"))

2. 循环爬取所有页面的推文文本

根据页面结构,有两种提取方式:

方式一:直接从列表页提取文本(如果列表页展示完整内容)

如果列表页的推文卡片里已经包含完整文本,直接用CSS选择器提取:

all_tweets <- c()

for(page in 1:total_pages) {
  current_page <- read_html(sprintf(base_url, page))
  # 替换为实际的推文文本容器选择器,比如.tweet-card内的文本节点
  tweet_texts <- html_text(html_nodes(current_page, ".tweet-card .tweet-text"))
  
  all_tweets <- c(all_tweets, tweet_texts)
  Sys.sleep(2) # 延迟避免触发反爬机制
}

# 查看结果
head(all_tweets)

方式二:进入详情页提取完整文本(如果列表页仅展示部分内容)

如果列表页只显示推文链接,需要先获取详情页URL,再逐个访问提取文本:

all_tweets <- list()

for(page in 1:total_pages) {
  current_page <- read_html(sprintf(base_url, page))
  # 获取推文详情页的相对链接
  tweet_hrefs <- html_attr(html_nodes(current_page, ".tweet-card"), "href")
  full_links <- paste0("https://polititweet.org", tweet_hrefs)
  
  # 遍历当前页的所有推文详情页
  page_tweets <- lapply(full_links, function(link) {
    tryCatch({
      tweet_page <- read_html(link)
      # 替换为详情页中推文文本的实际选择器
      text <- html_text(html_nodes(tweet_page, ".tweet-full-content"))
      Sys.sleep(1) # 单条请求延迟
      return(text)
    }, error = function(e) {
      message(paste("Failed to fetch", link))
      return(NA)
    })
  })
  
  all_tweets[[page]] <- unlist(page_tweets)
  Sys.sleep(2) # 页面间延迟
}

# 合并所有推文为向量
all_tweets_flat <- unlist(all_tweets)

关键注意事项

  • 选择器验证:用浏览器开发者工具(F12)确认目标元素的CSS选择器,网站更新后可能需要调整。
  • 反爬规避:必须添加Sys.sleep()控制请求频率,否则可能被网站封禁IP。
  • 异常处理:加入tryCatch()可以捕获请求失败的情况,避免循环中途中断。

内容的提问来源于stack exchange,提问作者derhard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 11:31:13