R:将网页抓取到包含元素和子元素的列表树中
R: webscraping into a tree of list with elements and subelements
使用 rvest
,我抓取了一个包含 4 个表格(<table class="ed-board-table">
)和 n 个表格的网页<td class="ed-board-member">
.
我希望将其放入 4 个元素和 n 个子元素的列表中。
也就是说,我的目标是在元素和子元素树中有一个列表(称为 editors
),如下所示:
editors
[[1]] # Table 1
[1] #Content 1 of Table 1
[2] #Content 2 of Table 1
[[2]] # Table 2
[1] #Content 1 of Table 2
[2] #Content 2 of Table 2
[3] #Content 3 of Table 2
[[3]] # Table 3
[1] #Content 1 of Table 3
[[4]] # Table 4
[1] #Content 1 of Table 4
到目前为止,我的代码使用 this website 未能完成此操作:
# extract the relevant part of the webpage [WORKS FINE]
webpage <- read_html(url("https://journals.sagepub.com/editorial-board/asr")) %>%
html_nodes(xpath='//*[@id="5dfa7b11-3157-4585-b786-54aa88233446"]/div/div/div')
# extract 4 tables into a list of 4 elements [WORKS FINE]
editors <- webpage %>%
html_nodes(xpath="//table[@class='ed-board-table']")
# extract the tables' n contents into n subelements [DOES NOT WORK]
editors2 <- sapply(editors,
function(x)
{
x %>%
html_nodes(xpath="//td[@class='ed-board-member']")
}
)
不幸的是,结果是 4 个元素的列表(这是正确的),每个 包含来自 <td class="ed-board-member">
来自 所有 个表。
我怎样才能得到一个 4 个元素(<table>
)的列表,其中只有那些属于 <td>
的子元素各自element/table?
这是你想要的吗?
read_html("https://journals.sagepub.com/editorial-board/asr") %>%
html_nodes(xpath = "//div[@class='editorial-board']/descendant::table") %>%
html_table(fill = TRUE)
使用 rvest
,我抓取了一个包含 4 个表格(<table class="ed-board-table">
)和 n 个表格的网页<td class="ed-board-member">
.
我希望将其放入 4 个元素和 n 个子元素的列表中。
也就是说,我的目标是在元素和子元素树中有一个列表(称为 editors
),如下所示:
editors
[[1]] # Table 1
[1] #Content 1 of Table 1
[2] #Content 2 of Table 1
[[2]] # Table 2
[1] #Content 1 of Table 2
[2] #Content 2 of Table 2
[3] #Content 3 of Table 2
[[3]] # Table 3
[1] #Content 1 of Table 3
[[4]] # Table 4
[1] #Content 1 of Table 4
到目前为止,我的代码使用 this website 未能完成此操作:
# extract the relevant part of the webpage [WORKS FINE]
webpage <- read_html(url("https://journals.sagepub.com/editorial-board/asr")) %>%
html_nodes(xpath='//*[@id="5dfa7b11-3157-4585-b786-54aa88233446"]/div/div/div')
# extract 4 tables into a list of 4 elements [WORKS FINE]
editors <- webpage %>%
html_nodes(xpath="//table[@class='ed-board-table']")
# extract the tables' n contents into n subelements [DOES NOT WORK]
editors2 <- sapply(editors,
function(x)
{
x %>%
html_nodes(xpath="//td[@class='ed-board-member']")
}
)
不幸的是,结果是 4 个元素的列表(这是正确的),每个 包含来自 <td class="ed-board-member">
来自 所有 个表。
我怎样才能得到一个 4 个元素(<table>
)的列表,其中只有那些属于 <td>
的子元素各自element/table?
这是你想要的吗?
read_html("https://journals.sagepub.com/editorial-board/asr") %>%
html_nodes(xpath = "//div[@class='editorial-board']/descendant::table") %>%
html_table(fill = TRUE)