【问题标题】:rvest function html_nodes returns {xml_nodeset (0)}rvest 函数 html_nodes 返回 {xml_nodeset (0)}
【发布时间】:2023-12-02 23:36:01
【问题描述】:

我正在尝试抓取以下网站的数据框

http://stats.nba.com/game/0041700404/playbyplay/

我想创建一个表格,其中包含比赛日期、整个比赛的得分以及球队名称

我正在使用以下代码:

game1 <- read_html("http://stats.nba.com/game/0041700404/playbyplay/")

#Extracts the Date
html_nodes(game1, xpath = '//*[contains(concat( " ", @class, " " ), concat( " ", "game-summary-team--vtm", " " ))]//*[contains(concat( " ", @class, " " ), concat( " ", "game-summary-team__lineup", " " ))]')

#Extracts the Score
html_nodes(game1, xpath = '//*[contains(concat( " ", @class, " " ), concat( " ", "status", " " ))]//*[contains(concat( " ", @class, " " ), concat( " ", "score", " " ))]')

#Extracts the Team names
html_nodes(game1, xpath = '//*[contains(concat( " ", @class, " " ), concat( " ", "game-summary-team__name", " " ))]//a')

不幸的是,我得到以下内容

{xml_nodeset (0)}
{xml_nodeset (0)}
{xml_nodeset (0)}

我已经看到了很多关于这个问题的问题和答案,但似乎都没有帮助。

【问题讨论】:

    标签: r xpath web-scraping css-selectors rvest


    【解决方案1】:

    不幸的是,rvest 不能很好地处理动态创建的 JavaScript 页面。它最适用于静态 HTML 网页。

    我建议看看RSelenium。最后,我使用rsDriver从页面中得到了一些东西

    代码示例:

    library(RSelenium)
    rD <- rsDriver() # runs a chrome browser, wait for necessary files to download
    remDr <- rD$client
    #no need for remDr$open() browser should already be open
    remDr$navigate("http://stats.nba.com/game/0041700404/playbyplay/")
    
    teams <- remDr$findElement(using = "xpath", "//span[@class='team-full']")
    teams$getElementText()[[1]]
    # and so on...
    
    remDr$close()
    # stop the selenium server
    rD[["server"]]$stop() 
    # if user forgets to stop server it will be garbage collected.
    rD <- rsDriver()
    rm(rD)
    gc(rD)
    

    等等……

    PS:我在使用当前 R 的 Windows 上安装它时遇到了一些麻烦 * 这个worked * How to set up rselenium for R?

    【讨论】:

      【解决方案2】:

      我在 R 中成功使用了 splashr 包。要安装,您需要 docker。下面列出的网站中提到了安装说明

      https://cran.r-project.org/web/packages/splashr/vignettes/intro_to_splashr.html

      https://docs.docker.com/docker-for-mac/install/#install-and-run-docker-for-mac - 如何在 Mac 上安装和运行 docker

      https://splash.readthedocs.io/en/stable/install.html - 在使用 splashr 之前在终端窗口中输入这些代码

      【讨论】:

      • 欢迎来到 Stack Overflow!虽然链接是分享知识的好方法,但如果它们在未来被破坏,它们将无法真正回答问题。将回答问题的链接的基本内容添加到您的答案中。如果内容太复杂或太大而无法在此处放置,请描述所提出解决方案的总体思路。请记住始终保留对原始解决方案网站的链接引用。见:How do I write a good answer?