【问题标题】:web scraping - No records found网络抓取 - 未找到记录
【发布时间】:2017-02-07 14:31:41
【问题描述】:

我正在尝试 rbind 系列 HTML 表(来自具有相同 col 名称的不同页面),但有些页面“没有记录”,我想跳过这些页面或将 NULL 分配给数据框。

示例数据框 1

url="http://stats.espncricinfo.com/ci/engine/player/28081.html?class=2;filter=advanced;floodlit=1;innings_number=1;orderby=start;result=1;template=results;type=batting;view=match"

Batting=readHTMLTable(url)

Batting$"Match by match list"

Batting<-Batting$"Match by match list"

数据框 2

    url="http://stats.espncricinfo.com/ci/engine/player/625383.html?class=2;filter=advanced;floodlit=1;innings_number=1;orderby=start;result=2;template=results;type=batting;view=match"



Batting=readHTMLTable(url)

Batting$"Match by match list"

Batting<-Batting$"Match by match list"

有几个这样的 Dataframes 有表格形式的记录,有些没有记录

当我 rbind 没有记录的时候导致最终数据帧出错

final_DF<-rbind(Dataframe1,Dataframe2)

我该如何解决这个问题!?

PS:对于每个 url 查询,我会根据我对数据框的要求添加某些列集(比如使用 cbind 的 5 个附加列)。

【问题讨论】:

    标签: html r xml dataframe web-scraping


    【解决方案1】:

    您可以执行以下操作:

    require(rvest)
    require(tidyverse)
    
    urls <- c(
      "http://stats.espncricinfo.com/ci/engine/player/28081.html?class=2;filter=advanced;floodlit=1;innings_number=1;orderby=start;result=1;template=results;type=batting;view=match",
      "http://stats.espncricinfo.com/ci/engine/player/625383.html?class=2;filter=advanced;floodlit=1;innings_number=1;orderby=start;result=2;template=results;type=batting;view=match"
    )
    
    extra_cols <- list(
      tibble("Team"="IND","Player"="MS.Dhoni","won"=1,"lost"=0,"D"=1,"D/N"=0,"innings"=1,"Format"="ODI"),
      tibble("Team"="IND","Player"="MS.Dhoni","won"=1,"lost"=0,"D"=1,"D/N"=0,"innings"=1,"Format"="ODI")
    )
    
    doc <- map(urls, read_html) %>% 
      map(html_node, ".engineTable:nth-child(5)")
    
    keep <- map_lgl(doc, ~class(.) != "xml_missing")
    
    map(doc[keep], html_table, fill = TRUE) %>% 
      map2_df(extra_cols[keep], cbind)
    

    关键部分是discard,它删除了类 "xml_missing" 的所有列表元素,例如空的。

    我与您的代码比较,我使用 CSS 选择器来指定应该继承表的 html_node。见http://selectorgadget.com/

    您的rbind 也是由map2_df(最后一行)在内部完成的

    这导致:(使用%&gt;% {head(.[,c("Bat1", "Runs", "Team")])}

      Bat1 Runs Team
    1    0    0  IND
    2    3    3  IND
    3  148  148  IND
    4   56   56  IND
    5   38   38  IND
    6   20   20  IND
    

    【讨论】:

    • 实际上我为每个 url 添加了额外的列,(例如: cbind("Team"="IND","Player"="MS.Dhoni","won"=1,"lost "=0,"D"=1,"D/N"=0,"innings"=1,"Format"="ODI") .
    • @chdeepak 查看我的更新。这样您就可以将附加信息绑定到抓取的数据中。
    • 感谢您的回复,我已尝试使用更新的代码。我添加了额外的网址。它抛出错误#### bind_rows_(x, .id) 中的错误:无法在“运行”列中自动从字符转换为整数。
    • 那么请正确设置列类型。我认为这个问题得到了回答。识别/隔离错误并用它打开一个新问题。
    • 是的....我同意。谢谢你的时间。抱歉,我之前的编辑在回答中意外发生了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 2020-05-20
    • 2018-12-03
    • 1970-01-01
    • 2021-09-01
    相关资源
    最近更新 更多