首页 > 解决方案 > 在 R 中使用 xpath 抓取数据表

问题描述

我对 R 相当熟悉,但对网页抓取的经验为 0。我环顾四周,似乎无法弄清楚为什么我的网络抓取“失败”。这是我的代码,包括我要抓取的 URL(具体的 ngs-data-table):

library(rvest)
webpage <- read_html("https://nextgenstats.nfl.com/stats/rushing/2020/REG/1#yards")
tbls <- html_nodes(webpage, xpath = '/html/body/div[2]/div[3]/main/div/div/div[3]')
#also attempted using this Xpath '//*[@id="stats-rushing-view"]/div[3]' but neither worked
tbls

我没有收到任何代码错误,但我收到:

{xml_nodeset (0)}

我知道这不是很多代码,我也尝试了多种不同的 xpath。我知道我最终将需要更多的代码来更具体地用于网络抓取,但我认为即使是上面的代码也至少会开始为我指明正确的方向?任何帮助,将不胜感激。谢谢!

标签: rxpathweb-scraping

解决方案


数据存储为 JSON。这是一种下载和处理该文件的方法。

library(httr)

#URL for week 6 data
url <- "https://nextgenstats.nfl.com/api/statboard/rushing?season=2020&seasonType=REG&week=6"

#create a user agent 
ua <- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"

#download the information
content <-httr::GET(url, verbose() , user_agent(ua), add_headers(Referer =  "https://nextgenstats.nfl.com/stats/rushing/2020/REG/1"))
answer <-jsonlite::fromJSON(content(content, as = "text") ,flatten = TRUE)
answer$stats

推荐阅读