代码之家  ›  专栏  ›  技术社区  ›  maru1898

Rvest html_节点跨div其他项

  •  0
  • maru1898  · 技术社区  · 3 年前

    我正在浏览这个html,我想提取 <span data-testid="distance">

    <span class="class1">
    <span data-testid="distance">the text i want</span>
    </span>
    <span class="class2">
    <span class="class1"><span>the other text i'm obtaining</span>
    </span>
    
    distancia <- hoteles_verdes %>% 
      html_elements("span.class1") %>%
      html_text()
    

    问题是如何隔离html元素上的数据testid=“distance”,以便以后检索html_文本。

    这是我的第一个问题帖子。谢谢

    0 回复  |  直到 3 年前
        1
  •  0
  •   neilfws    3 年前

    你可以用 CSS attribute selector .

    例如,要选择的[attribute |=“value”]选择器 attribute “数据测试”与 value =“距离”(注意单引号和双引号):

    library(rvest)
    
    hoteles_verdes %>% 
      html_nodes('[data-testid|="distance"]') %>% 
      html_text()
    

    结果:

    [1] "the text i want"
    

    数据:

    hotel_verdes <- read_html('<span class="class1">
                               <span data-testid="distance">the text i want</span>
                               </span>
                               <span class="class2">
                               <span class="class1"><span>the other text im obtaining</span>
                               </span>')
    
    推荐文章