【问题标题】:Scraping web table using R and rvest使用 R 和 rvest 抓取网页表
【发布时间】: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()

【问题讨论】:

    标签: html r rvest


    【解决方案1】:

    数据来自刷新页面时您可以在网络选项卡中看到的另一个端点。您可以在参数中使用您的搜索短语发送请求,然后从响应中提取您需要的 json。

    library(httr)
    library(jsonlite)
    
    params = list('k' = 'saperda tridentata','s' = 1,'m' = 1,'t' = 0)
    r <- httr::GET(url = 'https://gd.eppo.int/ajax/search', query = params)
    data <- jsonlite::parse_json(r %>% read_html() %>% html_node('p') %>%html_text())
    print(data[[1]]$e)
    

    【讨论】:

    • 谢谢@QHarr! :)
    猜你喜欢
    • 2015-09-06
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 2020-07-18
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多