首页 > 解决方案 > 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()```

标签: rrvest

解决方案


与大多数现代数据丰富的网页一样,您要查找的数据不在由 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 日创建


推荐阅读