gpt4 book ai didi

r - 如何使用 R 中的 purrr 映射函数将 xml-nodesets(使用 rvest 创建)放入小标题中?

转载 作者:行者123 更新时间:2023-12-04 03:33:27 25 4
gpt4 key购买 nike

我想抓取大量网站。为此,我首先阅读网站的 html 脚本并将它们存储为 xml_nodesets。由于我只需要网站的内容,我最后从 xml_nodesets 中提取每个网站的内容。为此,我编写了以下代码:

# required packages
library(purrr)
library(dplyr)
library(xml2)
library(rvest)

# urls of the example sources
test_files <- c("https://en.wikipedia.org/wiki/Web_scraping", "https://en.wikipedia.org/wiki/Data_scraping")

# reading in the html sources, storing them as xml_nodesets
test <- test_files %>%
map(., ~ xml2::read_html(.x, encoding = "UTF-8"))

# extracting selected nodes (contents)
test_tbl <- test %>%
map(., ~tibble(
# scrape contents
test_html = rvest::html_nodes(.x, xpath = '//*[(@id = "toc")]')
))
不幸的是,这会产生以下错误:
Error: All columns in a tibble must be vectors.
x Column `test_html` is a `xml_nodeset` object.
我想我明白这个错误的实质,但我找不到解决方法。这也有点奇怪,因为我在一月份能够顺利运行这段代码,突然它不再起作用了。我怀疑包更新是原因,但安装旧版本的 xml2、rvest 或 tibble 也无济于事。此外,仅抓取一个网站也不会产生任何错误:
test <- read_html("https://en.wikipedia.org/wiki/Web_scraping", encoding = "UTF-8") %>%
rvest::html_nodes(xpath = '//*[(@id = "toc")]')
你对如何解决这个问题有什么建议吗?非常感谢!
编辑:我删除了 %>% html_text从 ...
test_tbl <- test %>%
map(., ~tibble(
# scrape contents
test_html = rvest::html_nodes(.x, xpath = '//*[(@id = "toc")]')
))
...因为这不会产生此错误。不过,编辑过的代码确实如此。

最佳答案

您需要将对象存储在列表中。

test %>%
purrr::map(~tibble(
# scrape contents
test_html = list(rvest::html_nodes(.x, xpath = '//*[(@id = "toc")]'))
))

#[[1]]
# A tibble: 1 x 1
# test_html
# <list>
#1 <xml_ndst>

#[[2]]
# A tibble: 1 x 1
# test_html
# <list>
#1 <xml_ndst>

关于r - 如何使用 R 中的 purrr 映射函数将 xml-nodesets(使用 rvest 创建)放入小标题中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67419847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com