【发布时间】:2021-08-19 11:02:18
【问题描述】:
我从网上抓取了一堆数据:
source <- "https://www.ifad.org/en/web/operations/-/project/1100000001" #example data
html_out <- read_html(source)
temp_list <- html_out %>%
html_node(".project-row")
> temp_list
{html_node}
<div class="m-3 project-row">
[1] <dd class="project-status mt-3">\r\n <span>Status: Closed</span>\r\n ...
[2] <dt class="project-row-title">Country</dt>
[3] <dd class="project-row-text">\r\n <a href="/en/web/operations/w/country/dominican-republic ...
[4] <dt class="project-row-title">Approval Date</dt>
[5] <dd class="project-row-text">19 December 1979</dd>
[6] <dt class="project-row-title">Duration</dt>
[7] <dd class="project-row-text">1979 - 1988</dd>
[8] <dt class="project-row-title">Sector</dt>
[9] <dd class="project-row-text">Settlement</dd>
[10] <dt class="project-row-title">\r\nTotal Project Cost </dt>
我现在想对这些数据执行一些操作,这可能需要列表格式并且应该返回列表格式。比如下面这些:
temp_list <- temp_list %>%
gsub("^ *|(?<= ) | *$", "", ., perl = TRUE) %>% # removing multiple spaces
gsub("\r\n", "", .) # remove \r\n
for (j in 1:length(temp_list)) {
temp_list[j] <- #do more stuff here
}
我还不太明白 html_nodes 是如何工作的,但显然不像列表。例如,length(temp_list) 产生 2 而不是 10。 gsub() 命令不返回列表,而是返回一个长字符串。我试过lapply(X = ., FUN = function (t) gsub(pattern = "^ *|(?<= ) | *$", replacement = "", x = t, fixed = TRUE)) 来解决这个问题,但它返回一个错误:cannot coerce type 'externalptr' to vector of type 'character'
如何从 html_node 中创建一个列表或其他可行的格式? Here 建议使用bind_rows(lapply(xml_attrs(temp_list ), function(x) data.frame(as.list(x), stringsAsFactors=FALSE))),但这只会产生m-3 project-row。我也尝试按照建议的here 使用xmlValue(),但没有成功。
所有这些都在我之前的脚本版本中运行,我只是简单地写了(尽管承认不是很优雅):
temp_list <- html_out%>%
html_nodes(".project-row") %>%
as_list(.) %>%
unlist(., use.names= FALSE) %>%
as.list(.) %>%
gsub("^ *|(?<= ) | *$", "", ., perl = TRUE) %>% # removing multiple spaces
gsub("\r\n", "", .) # remove \r\n
由于某种原因,它不再起作用了,即使我不记得对我的这部分代码或输入数据进行了任何更改。
【问题讨论】:
-
你能分享你从哪里抓取数据的网页的网址吗?
-
这是这个页面:ifad.org/en/web/operations/-/project/1100000001。我在问题中添加了它。
-
你想从链接中提取什么?您的预期输出是什么?
-
最终的预期输出是一个有几列和两行的表格,其中包含该页面的所有数据。例如。批准日期:1979年12月19日;持续时间:1979 - 1988。我已经编写了脚本来做到这一点,并且它之前工作过。我的问题是指如何将 html_node 类型转换为列表(我的预期输出)。我想要一个列表来使用
temp_list[j]从节点中读取数据并应用gsub()之类的命令,这些命令适用于列表但不适用于html_node。