R:抓取到包含元素和子元素的列表树

时间:2020-10-03 16:56:41

标签: r list xpath web-scraping rvest

我使用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">中的内容所有表。

如何完成一个{strong> 4 个元素(<table>)的列表,而这些元素仅属于(<{> 1}的那些子元素(<td>)< / em>元素/表格?

1 个答案:

答案 0 :(得分:1)

这是您想要的吗?

read_html("https://journals.sagepub.com/editorial-board/asr") %>% 
  html_nodes(xpath = "//div[@class='editorial-board']/descendant::table") %>%  
  html_table(fill = TRUE)