【问题标题】:R: webscraping into a tree of list with elements and subelementsR:网页抓取到带有元素和子元素的列表树
【发布时间】:2021-01-19 00:41:49
【问题描述】:

使用 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 个元素的列表(这是正确的),每个包含来自 all<td class="ed-board-member"> 的内容/em> 表格。

我如何才能拥有一个 4 元素(&lt;table&gt;)列表,其中只有属于 相应 元素的那些子元素(&lt;td&gt;) /桌子?

【问题讨论】:

    标签: r list xpath web-scraping rvest


    【解决方案1】:

    这是你想要的吗?

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

    【讨论】:

      猜你喜欢
      • 2021-01-19
      • 2018-12-27
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      相关资源
      最近更新 更多