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

如何处理WHO网站下拉表单,爬取并下载新闻发布会记录PDF?

解决WHO官网Press Briefing transcript PDF爬取的修改步骤

1. 报错根源排查

cannot open URL 'NA'的核心问题是脚本未正确提取到筛选后的PDF链接,原因通常是:

  • WHO的「WHO document type」下拉菜单依赖JavaScript动态渲染,静态爬取(如直接用rvest::read_html)无法获取筛选后的页面内容
  • 链接提取的CSS/XPath路径错误,导致返回NA值

2. 替换为动态渲染爬取方案

由于目标页面的筛选功能依赖JS,建议用RSelenium模拟浏览器操作完成筛选,具体步骤如下:

2.1 安装并加载依赖包

install.packages(c("RSelenium", "rvest", "dplyr", "stringr"))
library(RSelenium)
library(rvest)
library(dplyr)
library(stringr)

2.2 启动浏览器驱动并导航到目标页

# 启动Chrome驱动(需确保本地Chrome版本与驱动匹配)
driver <- rsDriver(browser = "chrome", chromever = "latest")
remDr <- driver[["client"]]

# 导航到WHO目标页面
remDr$navigate("https://www.who.int/publications/m")

2.3 模拟下拉菜单筛选操作

# 定位「WHO document type」下拉菜单并展开
doc_type_dropdown <- remDr$findElement(using = "xpath", value = "//select[@id='documentTypeId']")
doc_type_dropdown$clickElement()

# 选择「Press Briefing transcript」选项
target_option <- remDr$findElement(using = "xpath", value = "//option[text()='Press Briefing transcript']")
target_option$clickElement()

# 等待JS渲染筛选结果
Sys.sleep(3)

3. 提取PDF链接并批量下载

3.1 获取筛选后的页面源码

page_source <- remDr$getPageSource()[[1]]
html <- read_html(page_source)

3.2 正确提取并清洗PDF链接

# 提取所有PDF后缀的链接
pdf_links <- html %>%
  html_elements("a[href$='.pdf']") %>%
  html_attr("href") %>%
  # 去除链接后的冗余参数
  str_remove_all("\\?.*")

# 补全相对链接为绝对URL
pdf_links <- ifelse(str_detect(pdf_links, "^http"), pdf_links, paste0("https://www.who.int", pdf_links))

# 过滤NA值(直接解决你的报错)
pdf_links <- pdf_links[!is.na(pdf_links)]

3.3 批量下载至工作目录

for (link in pdf_links) {
  # 从链接中提取文件名
  filename <- basename(link)
  # 下载PDF(mode="wb"确保二进制文件下载正常)
  download.file(url = link, destfile = filename, mode = "wb")
  # 添加延迟避免触发反爬机制
  Sys.sleep(1)
}

4. 收尾清理

# 关闭浏览器和驱动
remDr$close()
driver$server$stop()

关键注意事项

  • 务必保证Chrome驱动版本与本地Chrome浏览器版本一致,否则RSelenium无法正常启动
  • 若页面存在分页,需额外模拟点击「下一页」按钮,循环提取所有页面的PDF链接
  • WHO官网有反爬机制,建议适当延长延迟时间(Sys.sleep(2-3)),避免IP被封禁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:15:37