r - 在 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。我知道我最终将需要更多的代码来更具体地用于网络抓取,但我认为即使是上面的代码也至少会开始为我指明正确的方向?任何帮助,将不胜感激。谢谢!
解决方案
数据存储为 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
推荐阅读
- c# - Unity:访问动画组件内的动画
- python - 从 Python 中的 JSON 对象中获取值并将它们分配给变量
- kubernetes - Kubernetes 中容器和 Pod 的磁盘空间分配
- elasticsearch - Elastic 的 Logstash 变异拆分不起作用
- python - 使用 UTF-8 编码创建新的 csv
- ios - iPad 上的 UIImagePickerController 为空白
- javascript - 我如何插入一个允许用户根据他们在搜索框中输入的内容来确定 URL 的功能
- pandas - 我无法将 github 数据链接上传到 Google Colab
- r - 使用每个查询限制的结果运行 BLS API 大型数据帧并在 R 中另存为数据帧
- python - 无法在 Python 中为 Google BigQuery 设置 PATH 变量 - unicode 错误