r - HTML Rvest 抓取不显示表格
问题描述
我无法从这个网站上抓取表格。当我在一个数据表之后,我得到的只是 1 行代码。网站在这里。 https://mc.championdata.com/anz_premiership/index.html?competitionid=11035&matchid=110350101 和我的代码如下。
库(xml2) 图书馆(rvest) 库(XML) 数据列表 = 列表() web<- render_html(url = 'https://mc.championdata.com/anz_premiership/index.html?competitionid=10574&matchid=105740101') #xpath = '//*[@id="cd6364_SHELL_grids"]/div[1]/table' #打印(xpath) #tables<- html_nodes(web, 'table') 跟踪<- 网络 %>% html_nodes(xpath = '//*[@id="cd6364_SHELL_grids"]/div[1]/table') %>% html_table()```
解决方案
与大多数现代数据丰富的网页一样,您要查找的数据不在由 http 请求发送到该 url 的 html 文档中。相反,您的浏览器会收到包含 javascript 代码的 html。您的浏览器可以运行此 javascript 代码,这会提示它进一步发送 http 请求以获取填充页面的实际序列化数据(通常为 json 格式)。当您使用 rvest 或使用其他静态网页抓取工具进行网页抓取时,原始 html 以纯文本形式接收,并且没有 javascript 引擎会自动对其生成 json 请求。
因此,您无法从该页面获取数据的原因是数据不在您下载的页面上。
为了解决这个问题,您必须使用 Web 浏览器中的控制台(通过 F12)并通过查看浏览器发出的 XHR 请求(或查找嵌入在 html 文本中的直接链接)来找出 json 所在的 url本身)。在您的情况下,json地址是https://mc.championdata.com/data/11035/fixture.json?_=1593081934709。
您可以直接解析 json 并将其塑造成这样的数据框:
url <- "https://mc.championdata.com/data/11035/fixture.json?_=1593081934709"
fixture <- jsonlite::read_json(url)$fixture$match
df <- do.call(rbind, lapply(fixture, function(x)
as.data.frame(x[names(x) %in% names(fixture[[20]])])))
dplyr::as_tibble(df)
#> # A tibble: 45 x 22
#> awaySquadName matchType homeSquadId homeSquadShortC~ homeSquadNickna~
#> <fct> <fct> <int> <fct> <fct>
#> 1 Central Pulse H 802 TAC Tactix
#> 2 Northern Mys~ H 8120 NS Stars
#> 3 WBOP Magic H 808 STE Steel
#> 4 Northern Mys~ H 809 WBM Magic
#> 5 Mainland Tac~ H 808 STE Steel
#> 6 Central Pulse H 8120 NS Stars
#> 7 Mainland Tac~ H 8120 NS Stars
#> 8 WBOP Magic H 802 TAC Tactix
#> 9 Southern Ste~ H 805 MYS Mystics
#> 10 Southern Ste~ H 8120 NS Stars
#> # ... with 35 more rows, and 17 more variables: matchStatus <fct>,
#> # roundNumber <int>, homeSquadName <fct>, awaySquadNickname <fct>,
#> # venueId <int>, awaySquadId <int>, venueCode <fct>, localStartTime <fct>,
#> # matchId <int>, finalCode <fct>, finalShortCode <fct>, venueName <fct>,
#> # utcStartTime <fct>, awaySquadCode <fct>, homeSquadCode <fct>,
#> # awaySquadShortCode <fct>, matchNumber <int>
由reprex 包(v0.3.0)于 2020 年 6 月 25 日创建
推荐阅读
- node.js - 如何避免输入与用户输入的相同的值?
- wpf - 按下按钮时WPF失去焦点不会触发
- aframe - 如何将激光的点击绑定到拇指左键?寻求解决激光点击和传送之间的冲突
- vue.js - v-for 循环遍历基于选择器的外部数组
- xcode - 从不同的 ViewController 访问信息
- excel - Excel 64 位 .xll 加载项安装静默失败
- spring-webflux - Spring WebFlux with MongoDB - 限制 SSE 客户端
- php - 尝试使用 typeahead.js 和 php 和 Ajax 获取 id 和 value
- python-3.x - 收到错误 ipykernel_launcher.py:错误:需要以下参数:-t//--template, -i//--images
- java - 在 SWT 小部件表中动态填充大量数据