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

在R中批量抓取多来源新闻URL并提取正文的技术问询

R语言批量抓取多源新闻正文的通用方案

针对你需要批量处理上万条不同媒体URL、提取并合并新闻正文的需求,以下是几种实用的解决方案:

一、用专用新闻提取包(最省心)

textreadr包的read_news函数专门针对新闻页面做了优化,能自动识别不同网站的正文结构,无需手动指定CSS选择器,还能直接合并分段内容:

# 安装依赖包
install.packages(c("textreadr", "tidyverse"))
library(textreadr)
library(tidyverse)

# 假设你的URL数据存放在dataframe中
news_df <- tibble(
  url = c(
    "https://www.pilotonline.com/news/vp-nw-rally-roe-v-wade-20220504-xs6i4unvhfgn7i4ghbvlni3ysu-story.html#ed=rss_www.pilotonline.com/arcio/rss/category/government/virginia/",
    "https://www.washingtonpost.com/politics/2022/05/05/democrats-pressure-biden-administration-come-up-with-plan-counter-roe-demise/"
  )
)

# 批量提取并生成正文列
news_df <- news_df %>%
  mutate(full_text = map_chr(url, function(target_url) {
    tryCatch(
      {
        # 提取正文并合并分段
        paste(read_news(target_url), collapse = "\n")
      },
      error = function(e) NA_character_ # 抓取失败时返回NA
    )
  }))

二、自定义通用选择器方案(灵活可控)

如果需要更自主的控制,可以总结新闻网站常见的正文容器特征,用多优先级选择器依次尝试,确保覆盖多数网站:

library(rvest)
library(tidyverse)

# 定义通用选择器列表,按匹配优先级排序
common_selectors <- c(
  ".body-paragraph", ".article-body p", 
  "div[class*='content'] p", "article p", 
  "#main-content p", ".story-content p"
)

# 自定义提取函数
extract_clean_text <- function(target_url) {
  tryCatch(
    {
      page <- read_html(target_url)
      # 依次尝试选择器,拿到非空内容就停止
      for (selector in common_selectors) {
        text_segs <- page %>% html_nodes(selector) %>% html_text(trim = TRUE)
        if (length(text_segs) > 0) {
          return(paste(text_segs, collapse = "\n"))
        }
      }
      NA_character_ # 所有选择器都匹配失败
    },
    error = function(e) NA_character_ # 处理网络或解析错误
  )
}

# 批量处理URL
news_df <- news_df %>%
  mutate(full_text = map_chr(url, extract_clean_text))

三、大规模抓取的关键注意事项

  • 错误容错:必须用tryCatch包裹抓取逻辑,避免单个URL的异常中断整个批量任务。
  • 速率控制:针对上万条URL,一定要添加请求延迟(比如Sys.sleep(0.5)),或者用furrr做并行抓取时控制并行数,防止被目标网站封禁IP。
  • 结果校验:抓取完成后抽样检查full_text列,对提取失败的URL单独补充对应网站的选择器,逐步优化选择器列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:10:33