【发布时间】:2020-03-09 20:26:25
【问题描述】:
我是使用 R 进行网页抓取的新手。 我正在尝试抓取此链接生成的表格: https://gd.eppo.int/search?k=saperda+tridentata。 在这种特定情况下,它只是表中的一条记录,但可能更多(我实际上对第一列感兴趣,但整个表都可以)。
我尝试遵循 Allan Cameron 在此处 (rvest, table with thead and tbody tags) 给出的建议,因为问题似乎完全相同,但可能因为我对网页的工作原理知之甚少而没有成功。我总是得到一个“无数据”表。也许我没有正确遵循建议的步骤“# Get the JSON as plain text from the link generated by Javascript on the page”。 我在哪里可以得到这个链接?在这种特定情况下,我使用了“https://gd.eppo.int/media/js/application/zzsearch.js?7”,是这个吗?
下面有我的代码。 提前谢谢!
library(httr)
library(rlist)
library(rvest)
library(jsonlite)
library(dplyr)
pest.name <- "saperda+tridentata"
url <- paste("https://gd.eppo.int/search?k=",pest.name, sep="")
resp <- GET(url) %>% content("text")
json_url <- "https://gd.eppo.int/media/js/application/zzsearch.js?7"
JSON <- GET(json_url) %>% content("text", encoding = "utf8")
table_contents <- JSON %>%
{gsub("\\\\n", "\n", .)} %>%
{gsub("\\\\/", "/", .)} %>%
{gsub("\\\\\"", "\"", .)} %>%
strsplit("html\":\"") %>%
unlist %>%
extract(2) %>%
substr(1, nchar(.) -2) %>%
paste0("</tbody>")
new_page <- gsub("</tbody>", table_contents, resp)
read_html(new_page) %>%
html_nodes("table") %>%
html_table()
【问题讨论】: