在 R 中使用 `rvest` 使用 `read_html` 时缺少元素
Missing elements when using `read_html` using `rvest` in R
我正在尝试使用 rvest
包中的 read_html
函数,但遇到了一个我正在努力解决的问题。
例如,如果我试图阅读出现在 this 页面底部的 table,我将使用以下代码:
library(rvest)
html_content <- read_html("https://projects.fivethirtyeight.com/2016-election-forecast/washington/#now")
通过在浏览器中检查 HTML 代码,我可以看到我想要的内容包含在一个 <table>
标签中(具体来说,它都包含在 <table class="t-calc">
).但是当我尝试使用以下方法提取它时:
tables <- html_nodes(html_content, xpath = '//table')
我检索了以下内容:
> tables
{xml_nodeset (4)}
[1] <table class="tippingpointroi unexpanded">\n <tbody>\n <tr data-state="FL" class=" "> ...
[2] <table class="tippingpointroi unexpanded">\n <tbody>\n <tr data-state="NV" class=" "> ...
[3] <table class="scenarios">\n <tbody/>\n <tr data-id="1">\n <td class="description">El ...
[4] <table class="t-desktop t-polls">\n <thead>\n <tr class="th-row">\n <th class="t ...
其中包括页面上的一些 table 元素,但不是我感兴趣的元素。
任何关于我哪里出错的建议都将不胜感激!
table 是根据页面本身的 JavaScript 变量中的数据动态构建的。使用 RSelenium
在页面呈现后获取页面文本并将页面传递给 rvest
或者使用 V8
:
获取所有数据的宝库
library(rvest)
library(V8)
URL <- "http://projects.fivethirtyeight.com/2016-election-forecast/washington/#now"
pg <- read_html(URL)
js <- html_nodes(pg, xpath=".//script[contains(., 'race.model')]") %>% html_text()
ctx <- v8()
ctx$eval(JS(js))
race <- ctx$get("race", simplifyVector=FALSE)
str(race) ## output too large to paste here
如果他们改变了 JavaScript 的格式(这是一个自动化过程,所以不太可能,但你永远不知道)那么 RSelenium
方法会更好,前提是他们不改变格式table 结构(同样,不太可能,但你永远不知道)。
我正在尝试使用 rvest
包中的 read_html
函数,但遇到了一个我正在努力解决的问题。
例如,如果我试图阅读出现在 this 页面底部的 table,我将使用以下代码:
library(rvest)
html_content <- read_html("https://projects.fivethirtyeight.com/2016-election-forecast/washington/#now")
通过在浏览器中检查 HTML 代码,我可以看到我想要的内容包含在一个 <table>
标签中(具体来说,它都包含在 <table class="t-calc">
).但是当我尝试使用以下方法提取它时:
tables <- html_nodes(html_content, xpath = '//table')
我检索了以下内容:
> tables
{xml_nodeset (4)}
[1] <table class="tippingpointroi unexpanded">\n <tbody>\n <tr data-state="FL" class=" "> ...
[2] <table class="tippingpointroi unexpanded">\n <tbody>\n <tr data-state="NV" class=" "> ...
[3] <table class="scenarios">\n <tbody/>\n <tr data-id="1">\n <td class="description">El ...
[4] <table class="t-desktop t-polls">\n <thead>\n <tr class="th-row">\n <th class="t ...
其中包括页面上的一些 table 元素,但不是我感兴趣的元素。
任何关于我哪里出错的建议都将不胜感激!
table 是根据页面本身的 JavaScript 变量中的数据动态构建的。使用 RSelenium
在页面呈现后获取页面文本并将页面传递给 rvest
或者使用 V8
:
library(rvest)
library(V8)
URL <- "http://projects.fivethirtyeight.com/2016-election-forecast/washington/#now"
pg <- read_html(URL)
js <- html_nodes(pg, xpath=".//script[contains(., 'race.model')]") %>% html_text()
ctx <- v8()
ctx$eval(JS(js))
race <- ctx$get("race", simplifyVector=FALSE)
str(race) ## output too large to paste here
如果他们改变了 JavaScript 的格式(这是一个自动化过程,所以不太可能,但你永远不知道)那么 RSelenium
方法会更好,前提是他们不改变格式table 结构(同样,不太可能,但你永远不知道)。