【问题标题】:Scrape data within a table from webpage using rvest in R使用 R 中的 rvest 从网页中抓取表格中的数据
【发布时间】:2022-01-27 06:21:07
【问题描述】:

我正在尝试从此网页获取数据表:http://rotoguru1.com/cgi-bin/fyday.pl?week=1&game=dk&scsv=1

这是我要提取的数据的 XPath:/html/body/table/tbody/tr/td[3]/pre。

我试过了:

url <- "http://rotoguru1.com/cgi-bin/fyday.pl?week=1&game=dk&scsv=1"
DFS_table <- read_html(url) %>%
html_nodes(xpath = '/html/body/table/tbody/tr/td[3]/pre') %>%
html_table()
DFS_table<- DFS_table[[1]]

但出现此错误:DFS_table[[1]] 中的错误:下标超出范围。

当我尝试时:

url <- "http://rotoguru1.com/cgi-bin/fyday.pl?week=1&game=dk&scsv=1"
pg <- read_html(URL)
tab <- html_table(pg, fill=TRUE)[[1]]

似乎所有数据都显示在网页上,所以我想我的问题可能与整个页面是一个表格的事实有关,我需要提取其中的一部分,但我不确定该怎么做它。

感谢任何帮助。

【问题讨论】:

    标签: r html-table rvest


    【解决方案1】:

    html_table() 尝试读取格式正确的&lt;table&gt;[...]&lt;/table&gt;,看起来您感兴趣的数据是预格式化的文本。

    library(rvest)
    url <- "http://rotoguru1.com/cgi-bin/fyday.pl?week=1&game=dk&scsv=1"
    
    html <- read_html(url)
    text <- html_text(html_nodes(html, xpath = './/td[3]/pre'))
    
    library(stringi)
    str_split(text, "\n")
    

    这给了你:

      [1] "Week;Year;GID;Name;Pos;Team;h/a;Oppt;DK points;DK salary"   
      [2] "1;2021;1523;Mahomes II, Patrick;QB;kan;h;cle;36.28;8100"    
      [3] "1;2021;1537;Murray, Kyler;QB;ari;a;ten;34.56;7600"          
      [4] "1;2021;1490;Goff, Jared;QB;det;h;sfo;32.92;5100"            
      [5] "1;2021;1131;Brady, Tom;QB;tam;h;dal;32.16;6700"             
      [6] "1;2021;1501;Prescott, Dak;QB;dal;a;tam;31.42;6200" 
    

    【讨论】:

      【解决方案2】:

      我假设您想要“分号分隔格式:”行下的数据。这是预格式化的文本,因此无法尝试提取表节点。

      您可以将这些数据直接放入这样的数据框中。请注意 read.tablequote = 参数,这是必需的,因为某些玩家名称包含单引号。

      url <- "http://rotoguru1.com/cgi-bin/fyday.pl?week=1&game=dk&scsv=1"
      
      mydata <- read_html(u) %>% 
        html_node("pre") %>% 
        html_text() %>% 
        read.table(text = ., sep = ";", header = TRUE, quote = "")
      
      head(mydata)
      
        Week Year  GID                Name Pos Team h.a Oppt DK.points DK.salary
      1    1 2021 1523 Mahomes II, Patrick  QB  kan   h  cle     36.28      8100
      2    1 2021 1537       Murray, Kyler  QB  ari   a  ten     34.56      7600
      3    1 2021 1490         Goff, Jared  QB  det   h  sfo     32.92      5100
      4    1 2021 1131          Brady, Tom  QB  tam   h  dal     32.16      6700
      5    1 2021 1501       Prescott, Dak  QB  dal   a  tam     31.42      6200
      6    1 2021 1465     Winston, Jameis  QB  nor   h  gnb     29.62      5200
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-12
        • 1970-01-01
        • 1970-01-01
        • 2017-03-01
        • 1970-01-01
        • 2017-04-01
        相关资源
        最近更新 更多