html - 如何在 R 中使用 readHTMLTable 读取注释掉的 HTML 表格

标签 html r html-parsing

过去,我已经能够使用 R 中的 readHTMLTable 来提取一些足球统计数据。今年再次尝试这样做时,表格没有显示,即使它们在网页上可见。这是一个例子:http://www.pro-football-reference.com/boxscores/201609080den.htm

当我查看页面的源代码时,表格都被注释掉了(我怀疑这就是 readHTMLTable 找不到它们的原因)。

示例:在源代码中搜索“team_stats”...

    <!--  
    <div class="table_outer_container">
    <div class="overthrow table_container" id="div_team_stats">
    <table class="stats_table" id="team_stats" data-cols-to-  freeze=1><caption>Team Stats Table</caption>

问题:

表格如何在源代码中被注释掉而在浏览器中显示?

有没有办法使用 readHTMLTable(或其他方法)读取注释掉的表格?

最佳答案

事实上,如果您使用 XPath comment() 选择器,您可以获取它:

library(rvest)

url <- 'http://www.pro-football-reference.com/boxscores/201609080den.htm'

url %>% read_html() %>%                   # parse html
    html_nodes('#all_team_stats') %>%     # select node with comment
    html_nodes(xpath = 'comment()') %>%   # select comments within node
    html_text() %>%                       # return contents as text
    read_html() %>%                       # parse text as html
    html_node('table') %>%                # select table node
    html_table()                          # parse table and return data.frame

##                                 CAR           DEN
## 1         First Downs            21            21
## 2        Rush-Yds-TDs      32-157-1      29-148-2
## 3   Cmp-Att-Yd-TD-INT 18-33-194-1-1 18-26-178-1-2
## 4        Sacked-Yards          3-18          2-19
## 5      Net Pass Yards           176           159
## 6         Total Yards           333           307
## 7        Fumbles-Lost           0-0           1-1
## 8           Turnovers             1             3
## 9     Penalties-Yards          8-85          4-22
## 10   Third Down Conv.          9-15          5-10
## 11  Fourth Down Conv.           0-0           1-1
## 12 Time of Possession         32:19         27:41

关于html - 如何在 R 中使用 readHTMLTable 读取注释掉的 HTML 表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39420282/

相关文章:

r - dplyr group_by abs() 过滤数据

ruby - 使用 Nokogiri 从链接获取 href 时无法将字符串转换为整数

php - 将 HTML 文件解析为 PHP

javascript - 我如何让 Flash 重新加载它嵌入的父 HTML 页面?

javascript - 隐藏具有相同类的所有特定 div 的 Angular 方式是什么

html - 无法使从左到右的边框被覆盖

R ggplot2 : Barplot partial/semi stack

r - 如何将多个函数应用于R中的data.table

python - 如何使用 BeautifulSoup 获取两个指定标签之间的所有文本?

html - 列出顶部带有元素符号的元素