【问题标题】:{xml_nodeset (0)} problem when attempting to reproduce webscraping example (don't think it's a JS issue){xml_nodeset (0)} 尝试重现网页抓取示例时出现问题(不要认为这是 JS 问题)
【发布时间】:2019-08-18 22:48:54
【问题描述】:

我正在尝试使用rvest 学习网络抓取,并尝试重现此处给出的示例:

https://www.r-bloggers.com/using-rvest-to-scrape-an-html-table/

安装了rvest后,我只是复制粘贴了文章中给出的代码:

library("rvest")
url <- "http://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_population"
population <- url %>%
  read_html() %>%
  html_nodes(xpath='//*[@id="mw-content-text"]/table[1]') %>%
  html_table()
population <- population[[1]]

唯一的区别是我使用read_html() 而不是html(),因为后者已被弃用。

与文章中报告的输出不同,这段代码产生了熟悉的:

Error in population[[1]] : subscript out of bounds

其起源是在没有最后两行的情况下运行代码给population一个值{xml_nodeset (0)}

之前所有关于此的问题都表明这是由于表格在 javascript 中动态格式化造成的。但这里的情况并非如此(除非 Wikipedia 自 2015 年 rbloggers 文章以来已更改其格式)。

任何见解都将不胜感激,因为我不知所措!

【问题讨论】:

    标签: html r web-scraping rvest


    【解决方案1】:

    html 已更改。该 xpath 不再有效。您可以执行以下操作:

    library("rvest")
    url <- "http://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_population"
    population <- url %>%
      read_html() %>%
      html_node(xpath='//table') %>%
      html_table()
    

    由于我已切换到返回第一个匹配项的 html_node,因此我不再需要 [1] 的索引。

    较长的 xpath 现在在您的原始路径中有一个 div:

    //*[@id="mw-content-text"]/div/table[1]
    

    这就是你在浏览器中右键复制xpath得到的路径在桌子上。

    您要避免使用长 xpath,因为它们很脆弱,并且可以看出,当页面的 html 更改时很容易损坏。

    您也可以使用 css 并按类抓取(例如)

    library("rvest")
    url <- "http://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_population"
    population <- url %>%
      read_html() %>%
      html_node(css='.wikitable') %>%
      html_table()
    

    【讨论】:

    • 非常感谢!这两个都有效。当我有你的时候,我现在正试图从这个 url 中抓取第一个表:whoscored.com/Matches/318578/LiveStatistics/… 这一次,代码population &lt;- url %&gt;% read_html() %&gt;% html_node(xpath='//*[@id="top-player-stats-summary-grid"]')population 一个值{xml_missing} &lt;NA&gt; 你的css方法以'.grid'作为类产生相同的结果。你知道这里发生了什么吗?谷歌搜索建议一个 Javascript 问题,但我不确定该表是否为动态格式。
    • 确实,在js运行后会出现table(可以通过在浏览器中禁用js并刷新页面来验证)。如果您打开一个新问题并在此处放置一个链接,我会调查它。
    • 非常感谢您的提议 - 我在这里发布了一个新问题:stackoverflow.com/questions/57547825/… 我已经看到一些提到 RSelenium 的答案,但这对我来说似乎很慢,所以我不确定如果有更快的方法?抱歉,我真的对 javascript/html/除了 R 什么都不懂
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    相关资源
    最近更新 更多