【问题标题】:scrape multiple linked HTML tables in R and rvest在 R 和 rvest 中抓取多个链接的 HTML 表
【发布时间】:2015-04-28 01:34:54
【问题描述】:

这篇文章http://www.ajnr.org/content/30/7/1402.full 包含四个指向我想用rvest 抓取的html 表的链接。

借助 css 选择器:

"#T1 a" 

可以像这样到达第一张桌子:

library("rvest")
html_session("http://www.ajnr.org/content/30/7/1402.full") %>%
follow_link(css="#T1 a") %>%
html_table() %>%
View()

css 选择器:

".table-inline li:nth-child(1) a"

可以选择包含链接到四个表的标签的所有四个 html 节点:

library("rvest")
html("http://www.ajnr.org/content/30/7/1402.full") %>%
html_nodes(css=".table-inline li:nth-child(1) a")

如何遍历此列表并一次检索所有四个表?最好的方法是什么?

【问题讨论】:

标签: r web-scraping rvest


【解决方案1】:

你可能想使用如下:

main_url <- "http://www.ajnr.org/content/30/7/1402/"
urls <- paste(main_url,c("T1.expansion","T2.expansion","T3.expansion","T4.expansion"),".html", sep = "")
tables <- list()
for(i in seq_along(urls))
{
  total <- readHTMLTable(urls[i])
  n.rows <- unlist(lapply(total, function(t) dim(t)[1]))
  tables[[i]] <- as.data.frame(total[[which.max(n.rows)]])
}
tables

#[[1]]
#  Glioma Grade Sensitivity Specificity    PPV    NPV
#1    II vs III       50.0%       92.9%  80.0%  76.5%
#2     II vs IV      100.0%      100.0% 100.0% 100.0%
#3    III vs IV       78.9%       87.5%  93.8%  63.6%

#[[2]]
#  Glioma Grade Sensitivity Specificity   PPV    NPV
#1    II vs III       87.5%       71.4% 63.6%  90.9%
#2     II vs IV      100.0%       85.7% 90.5% 100.0%
#3    III vs IV       89.5%       75.0% 89.5%  75.0%

#[[3]]
#  Criterion Sensitivity Specificity    PPV   NPV
#1       ≥1*       85.2%       92.9%  95.8% 76.5%
#2        ≥2       81.5%      100.0% 100.0% 73.7%

#[[4]]
#  Criterion Sensitivity Specificity   PPV   NPV
#1     <1.92       96.3%       71.4% 86.7% 90.9%
#2     <2.02       92.6%       71.4% 86.2% 83.3%
#3    <2.12*       92.6%       85.7% 92.6% 85.7%

【讨论】:

  • 谢谢!是否可以创建一种更通用的方法,其中脚本提取表(或链接)的数量?这也可以用于同一期刊的其他文章。
【解决方案2】:

这是一种方法:

library(rvest)

url <- "http://www.ajnr.org/content/30/7/1402.full"
page <- read_html(url)

# First find all the urls
table_urls <- page %>% 
  html_nodes(".table-inline li:nth-child(1) a") %>%
  html_attr("href") %>%
  xml2::url_absolute(url)

# Then loop over the urls, downloading & extracting the table
lapply(table_urls, . %>% read_html() %>% html_table())

【讨论】:

  • 我试过这个,我收到一条错误消息:警告消息:'html'已被弃用。请改用“read_html”。查看帮助(“已弃用”)
  • 我通过在第三行替换 read_html(url) 来改变它。我仍然收到投诉。我做错了什么?
  • @PaulM 你可能错过了最后一行的那个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-19
  • 2015-11-02
  • 2021-11-17
  • 2023-03-10
  • 2019-02-16
  • 1970-01-01
  • 2018-08-26
相关资源
最近更新 更多