【发布时间】:2017-02-15 20:23:45
【问题描述】:
考虑一个有 4 个或更多列表 <li> html 元素的网站。
例如这样的网站:https://www.cprd.com/bibliography/bibliography.html
使用xml2(或其他方法,但首选xml2 和管道),将列表提取为字符向量的最佳方法是什么?
url <- 'https://www.cprd.com/bibliography/bibliography.html'
library(xml2)
page <- read_html(url)
输出应该是网站上的<li> 列表。 (每年有一份)
第一个列表的第一项应该等于“评估降糖药物发起者之间的通道偏差:一项英国队列研究。 Ankarfeldt MZ、Thorsted BL、Groenwold RH、Adalsteinsson E、Ali MS、Klungel OH。 临床流行病学。 2017;9:19–30。'
编辑:cmets 建议
library(rvest)
output<-page %>% html_nodes('ol') %>% lapply(html_nodes, 'li') %>% lapply(html_text, trim = TRUE)
output[[1]][1]
[1] "Assessment of channeling bias among initiators of glucose-lowering drugs: A UK cohort study. \r\n Ankarfeldt MZ, Thorsted BL, Groenwold RH, Adalsteinsson E, Ali MS, Klungel OH. Clin Epidemiol. 2017;9:19㤼㸶30."
【问题讨论】:
-
你有没有尝试过?你遇到了什么问题?
-
尝试为此使用
rvest包:library(rvest); read_html('https://www.cprd.com/bibliography/bibliography.html') %>% html_nodes('ol') %>% lapply(., function(x) html_nodes(x,'li') %>% html_text())。 -
@Abdou 如果你
lapply(或purrr::map,随着情况变得更复杂会变得更方便)两次,代码会更容易阅读:h2 %>% html_nodes('ol') %>% lapply(html_nodes, 'li') %>% lapply(html_text, trim = TRUE)Time-wise,它们几乎相同。
标签: r web-scraping xml2