我想为Type='AA‘的第一条记录自动提取链接并下载文件。
我设法提取了表,但是如何提取最后一列中'AA‘类型的链接呢?
library(rvest)
library(stringr)
url <- "https://beta.companieshouse.gov.uk/company/02280000/filing-history"
wahis.session <- html_session(url)
r <- wahis.session %>%
html_nodes(xpath = '//*[@id="fhTable"]') %>%
html_table(fill = T) 发布于 2019-06-22 10:51:39
我假设这个网站可以让你自动爬行,如果你不确定,可以检查它的robots.txt和网站的爬行策略。
实际上,你还有很多工作要做。
此脚本应该可以帮助您从单个页面中提取所需的报告。如果你想创建一个从所有页面中提取出来的脚本,我建议你去看看关于网络抓取的教程,比如这个https://www.datacamp.com/community/tutorials/r-web-scraping-rvest。
您可以查看的另一个包是Rcrawler,它将自动化脚本的许多提取部分,但需要您了解其功能。
library(rvest)
library(stringr)
url <- "https://beta.companieshouse.gov.uk/company/02280000/filing-history"
url2 <- "https://beta.companieshouse.gov.uk"
wahis.session <- html_session(url)
r <- wahis.session %>%
html_nodes(xpath = '//*[@id="fhTable"]') %>%
html_table(fill = T)
s <- wahis.session %>%
html_nodes(xpath = '//*[contains(concat( " ", @class, " " ), concat( " ", "download", " " ))]') %>%
html_attr("href")
r <- r[[1]] %>% as_tibble %>%
mutate(link = paste0(url2, s)) %>%
filter(Type == "AA")
n <- paste0("report",seq_along(r$link), ".pdf")
for(i in seq_along(n)) {
download.file(r$link[i], n[i], mode = "wb")
}发布于 2019-06-22 14:34:18
我将提取tr节点,使用purrr的map生成.filing-type的文本和.download的href属性的数据帧,使用dplyr的bind_rows堆叠数据帧,最后基于type == "AA"进行过滤
library(dplyr)
library(rvest)
library(purrr)
url <- "https://beta.companieshouse.gov.uk/company/02280000/filing-history"
html <- read_html(url)
html %>%
html_nodes("tr") %>%
map(~ tibble(type = html_text(html_node(., ".filing-type"), T),
href = html_attr(html_node(., ".download"), "href")
)) %>%
bind_rows() %>%
filter(type == "AA")这将返回"AA“类型文档的路径数据帧:
type href
<chr> <chr>
1 AA /company/02280000/filing-history/MzIxMjY0MDgxOGFkaXF6a2N4/document?format=pdf&download=0
2 AA /company/02280000/filing-history/MzE4NDAwMDg1NGFkaXF6a2N4/document?format=pdf&download=0现在,您只需要将域和路径粘贴在一起,然后使用base R的download.file或带有write_disk的rvest的GET来下载文件。
https://stackoverflow.com/questions/56711919
复制相似问题