首页 > 解决方案 > 使用 Rvest 进行网页抓取,UseMethod(“xml_find_first”)中的错误:没有适用于“字符”类对象的“xml_find_first”方法

问题描述

我正在尝试使用以下代码抓取几个网页

library(rvest)
library(dplyr)

    
    glasgow <- 'https://glasgow.gov.uk/article/24653/European-Settlement-Service'
    rsg <- 'https://www.romasupportgroup.org.uk/roma-and-brexit.html'
    
    urls<-c(rsg, glasgow)
    urls_rh<-map(urls, read_html)
    
    text <- map(urls_rh, html_node('.div'))

但我收到以下错误消息

UseMethod 中的错误(“xml_find_first”):没有适用于“字符”类对象的“xml_find_first”方法 Traceback:

  1. 地图(urls_rh,html_node(“.div”))
  2. as_mapper(.f, ...)
  3. html_node(".div")
  4. html_node.default(".div")
  5. xml2::xml_find_first(x, make_selector(css, xpath))

我也尝试使用 for 循环,结果相同

for (i in urls_rh){ 
  text <- html_node("div")
}

有什么建议吗?

标签: rweb-scrapingpurrrrvest

解决方案


您可以使用 :

library(rvest)
library(purrr)

text <- map(urls_rh, html_node, 'div')

或者也许更清楚:

text <- map(urls_rh, ~html_node(., 'div'))

推荐阅读