r - 将 tbl 超链接映射到 read_html
问题描述
我有一个包含一列的小标题,该列在每一列中存储超链接。现在我想使用 map_dfr 映射这些链接,通过read_html(.x[.x]) %>%
html_node(".body-copy-lg") %>% html_text
. 如果我这样做,我总是会遇到错误:
doc_parse_file 中的错误(con,encoding = encoding,as_html = as_html,options = options):期望单个字符串值:[type=character; 范围=3]。
这告诉我 read_html 基本上说:“嘿,不要同时向我扔多个字符串。”
那么我在映射器中犯了错误吗?这是一个错误吗?我真的不明白为什么映射器函数不会一个接一个地抓取每个元素。
到目前为止我尝试了什么:
target_regex <- "(xtm)|((k|K)(i|I|1|11)(d|D)(n|N).)|(Ar<e)\\s(you)\\s(in)|
(LOAN)|(AR(\\s|\\S)[0-9])|((B|b)(i|1|l)tc.)|(Coupon)|(Plastic.King)|(organs)|(SILI)|(Electric.Cigarette.Machine)"
adverts <- function(df) df[!grepl(target_regex, df$...1,perl = T), ]
bribe <- read_html(paste("http://ipaidabribe.com/reports/paid?page", 10, sep = "="))
report <- map(".read-more", ~html_nodes(bribe, .x) %>%
html_attr(.x[[1]][[1]][[1]], name = "href"))[[1]] %>%
as_tibble(.name_repair = "unique") %>%
bind_rows() %>%
rename( ...1 = value) %>%
adverts() %>%
map_dfr(~read_html(.x[.x]) %>%
html_node(".body-copy-lg") %>%
html_text)
不要介意调用which 基本上是为了在这种情况下可用而rename()
需要做的事情。adverts
解决方案
您忘记了 R 中的大多数函数都是矢量化的,并且不需要使用map
orapply
函数。在您的情况下,在获取 html 文本的最后一步中需要它。
您使用的语法map
也令人费解,我认为您应该查看?map
以更好地处理它。例如,您使用多个.x
或提取的值,您应该只是.x
用来引用您正在迭代的对象的子元素。
library(tidyverse)
library(rvest)
target_regex <- "(xtm)|((k|K)(i|I|1|11)(d|D)(n|N).)|(Ar<e)\\s(you)\\s(in)|
(LOAN)|(AR(\\s|\\S)[0-9])|((B|b)(i|1|l)tc.)|(Coupon)|(Plastic.King)|(organs)|(SILI)|(Electric.Cigarette.Machine)"
adverts <- function(df) df[!grepl(target_regex, df$...1,perl = T), ]
bribe <- read_html(paste("http://ipaidabribe.com/reports/paid?page", 10, sep = "="))
report <- html_nodes(bribe, ".read-more") %>%
html_attr("href") %>%
as_tibble(.name_repair = "unique") %>%
filter(str_detect(value, target_regex, negate = TRUE)) %>%
mutate(text = map_chr(value, ~read_html(.x) %>%
html_node(".body-copy-lg") %>%
html_text))
result
# A tibble: 3 x 2
value text
<chr> <chr>
1 http://ipaidabribe.com/reports/paid/paid-bribe-to-settle-matter… "\r\n Place: Nelamangala Police Station, Bangalore\nDate of incident: 5th Jan 2020, 3PM…
2 http://ipaidabribe.com/reports/paid/paid-500-rs-bribe-at-nizamu… "\r\n My Brother Mahesh Prasad travelling on PNR number 4822171124 train no 12721 Ni…
3 http://ipaidabribe.com/reports/paid/drone-air-follow-focus-wire… "\r\n This new Silencer Air+ is a tremendously versatile and resourceful follow focus, z…
推荐阅读
- c++ - set::find 查找不存在的元素
- tar - Deno:处理 tar 存档会导致校验和错误(标准库)
- amazon-web-services - 如何将域路由到 elastickbeanstalk?
- c++ - 如何解释c++11中的静态代码
- python - (PyQt5)如何在我的主窗口中显示一个新窗口?
- c - 停止主线程,直到所有其他线程完成
- c++ - 一般采用可索引/可调用的线性组合
- python - 如何在代码中强制自动重新加载 Flask?
- r - (434) WSA E TimedOut:丢失与 R 中 Teradata 服务器的套接字连接
- csv - 无法将 csv 文件加载到雪花中