任何HTML元素的获取样式属性



我有一个数据框架,其中一列是html。我试图推断每行是否粗体,斜体,什么字体大小等,如我在这里详细

下面是一些示例html:

<div align="justify" style="font-size: 10pt; margin-top: 10pt">n<b>ITEM 2. PROPERTIES</b>n</div>"

我现在正试图通过从每行获取style属性(如果存在)来解决这个问题。我该怎么做呢?到目前为止最接近的是

html %>% html_nodes(xpath="//div[contains(@style)]")

,但它不起作用,因为1)我不想仅限于div -我想要的样式从每一行,这可能或可能不是来自div。此外,与"包含",我找不到如何说我想要任何东西的样式是存在的,而不是等于一个特定的值。如果可能的话,我希望每个HTML字符串中的style元素,然后将其解析为诸如字体大小和margin-top之类的东西。由于

我不想只限制div -我想从每一个样式row,它可能来自也可能不是来自div。同样,使用"contains&quot不知道怎么说我想要有风格的东西小于等于一个特定的值

在节点/文档节点

上为样式属性使用属性选择器,而不指定属性值。

all_nodes_with_style <- html %>% html_nodes('[style]')
first_node_with_style <- html %>% html_node('[style]')

当使用 访问实际值时,如果不存在NA,则返回

NA。

html_attr('style')

library(rvest)
#> Loading required package: xml2
#> Warning: package 'xml2' was built under R version 4.0.3
library(purrr)
#> 
#> Attaching package: 'purrr'
#> The following object is masked from 'package:rvest':
#> 
#>     pluck
cases <- c('<a href="#" id="style" style="display: none;">Me</a>', '<a href="#" id="no_style" >Nope</a>')
map(cases , ~ read_html(.) %>% html_node('[style]') %>% html_attr('style'))
#> [[1]]
#> [1] "display: none;"
#> 
#> [[2]]
#> [1] NA

由reprex包(v0.3.0)创建于2021-02-10

最新更新