【问题标题】:lapply() with XPath to obtain all text after a specific tag not workinglapply() 使用 XPath 获取特定标记后的所有文本不起作用
【发布时间】:2021-01-15 14:26:05
【问题描述】:

背景:

我正在搜索this website,以获取编辑委员会相应部门下所有人员的名单。

总共有 6 个部分,每个部分都以 <b>...</b> 部分开头。 (其实应该是5,但是代码有点乱。)

我的目标:

我想获取每个部分的所有人的列表(包含 6 个元素的列表,称为 people)。

我的方法:

我尝试在每个相应的<b>...</b>-tag 之后获取所有文本或text()

但是,使用以下 R 代码和 XPath,我无法获得正确的列表:

journal_url <- "https://aepi.biomedcentral.com/about/editorial-board"

webpage <- xml2::read_html(url(journal_url))

# get a list of 6 sections
all_sections <- rvest::html_nodes(wholepage, css = '#editorialboard p')

# the following does not work properly
people <- lapply(all_sections, function(x) rvest::html_nodes(x, xpath = '//b/following-sibling::text()'))

错误的结果:

它不是给我一个包含每个部分的人的 6 个元素的列表,而是给我一个包含每个元素中的所有人的 6 个元素的列表。

预期结果:

预期的输出将以:

开头
people

[[1]]
[1] Shichuo Li

[[2]]
[1] Zhen Hong
[2] Hermann Stefan
[3] Dong Zhou

[[3]]
[1] Jie Mu

# etc etc

【问题讨论】:

    标签: r web-scraping xpath css-selectors rvest


    【解决方案1】:

    双正斜杠 xpath 选择整个文档中的所有节点,即使对象是单个节点。使用当前节点选择器.

    people <- lapply(all_sections, function(x) {
                       rvest::html_nodes(x, xpath = './b/following-sibling::text()')
                     })
    

    输出:

    [[1]]
    {xml_nodeset (1)}
    [1] Shichuo Li, 
    
    [[2]]
    {xml_nodeset (3)}
    [1] Zhen Hong, 
    [2] Hermann Stefan, 
    [3] Dong Zhou, 
    
    [[3]]
    {xml_nodeset (0)}
    
    [[4]]
    {xml_nodeset (1)}
    [1] Jie Mu, 
    
    [[5]]
    {xml_nodeset (2)}
    [1] Bing Liang, 
    [2] Weijia Jiang, 
    
    [[6]]
    {xml_nodeset (35)}
     [1] Aye Mye Min Aye, 
     [2] Sándor Beniczky, 
     [3] Ingmar Blümcke, 
     [4] Martin J. Brodie, 
     [5] Eric Chan, 
     [6] Yanchun Deng, 
     [7] Ding Ding, 
     [8] Yuwu Jiang, 
     [9] Hennric Jokeit, 
    [10] Heung Dong Kim, 
    [11] Patrick Kwan, 
    [12] Byung In Lee, 
    [13] Weiping Liao, 
    [14] Xiaoyan Liu, 
    [15] Guoming Luan, 
    [16] Imad M. Najm, 
    [17] Terence O'Brien, 
    [18] Jiong Qin, 
    [19] Markus Reuber, 
    [20] Ley J.W. Sander, 
    ...
    

    【讨论】:

      猜你喜欢
      • 2017-12-04
      • 2016-02-05
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多