【问题标题】:Selecting specific styles with rvest使用 rvest 选择特定样式
【发布时间】:2018-03-01 13:50:30
【问题描述】:

是否可以使用 rvest 仅抓取具有特定样式的文本?

示例 HTML:

<p>Lorem ipsum <span style="font-size: 15px">dolor</span> sit amet, <span style="font-size: 15px">consetetur</span> sadipscing <span style="font-weight: 400">elitr</span>, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam.</p>

我只想抓取带有font-size: 15px 的文本,而不是其他&lt;span&gt;-tags 中的文本。

我尝试过的一种解决方法是:

html %>% 
  html_nodes('span') %>% 
  str_subset('font-size: 15px')

但是,在str_subset 之后不能使用html_text,因为它将html 转换为字符串。除了手动擦除剩余的标签还有其他想法吗?

【问题讨论】:

    标签: r web-scraping rvest


    【解决方案1】:

    在 rvest 包中查找 html_attrhtml_attrs 函数。

    此示例将找到具有您要查找的属性的节点:

    library(rvest)
    
    html<-read_html('<p>Lorem ipsum <span style="font-size: 15px">dolor</span> sit amet, <span style="font-size: 15px">consetetur</span> sadipscing <span style="font-weight: 400">elitr</span>, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam.</p>')
    
    nodes<-html %>%   html_nodes('span') 
    nodes[html_attr(nodes, "style")=="font-size: 15px"]
    
    #{xml_nodeset (2)}
    #[1] <span style="font-size: 15px">dolor</span>
    #[2] <span style="font-size: 15px">consetetur</span>
    

    【讨论】:

    • 谢谢,这正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 2015-11-14
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多