首页 > 解决方案 > 将 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

标签: rrvestpurrr

解决方案


您忘记了 R 中的大多数函数都是矢量化的,并且不需要使用maporapply函数。在您的情况下,在获取 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…

推荐阅读