【问题标题】:Extract unique HTML tags from a document从文档中提取唯一的 HTML 标签
【发布时间】:2015-08-18 18:17:36
【问题描述】:

我在 R 中有一个 HTML 文档,我想从该文档中提取一个唯一标签列表,并计算它们的出现频率。

我可以按如下方式遍历每个可能的标签,但希望有一个不需要预定义标签列表的解决方案:

library('XML')
url <- 'http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array'
doc <- htmlParse(url)
all_tags <- c('//p', '//a', '//b', '//u', '//i')
counts <- sapply(all_tags, function(x) length(xpathSApply(doc, x)))
free(doc)

【问题讨论】:

  • table(xpathSApply(doc, "//*", xmlName))?
  • @lukeA 完美。让您的评论成为答案!
  • 同意@lukeA 将他的作为答案发布,并且应该接受他的作为答案。我只为使用xml2 的人发布了Hadleyverse 版本,并且故意不包括XML / xpathSApply,希望Luke 会发布答案。
  • @hrbrmstr 谢谢!

标签: xml r web-scraping


【解决方案1】:

经典的 XML 包版本可能如下所示:

tab <- table(xpathSApply(doc, "//*", xmlName))
tab[c('p', 'a', 'b', 'u', 'i')]

【讨论】:

    【解决方案2】:

    Hadleyverse 版本(但必要时会恢复到基础版本):

    library(xml2)
    library(dplyr)
    
    url <- 'http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array'
    doc <- read_html(url)
    tags <- xml_name(xml_find_all(doc, "//*"))
    
    # base version
    sort(table(tags))
    
    ## tags
    ##     body     form       h1     head     html    title      sub       h3        i noscript 
    ##        1        1        1        1        1        1        2        3        3        3 
    ##       h4       h2       th     link       hr       ol       ul       em    input        b 
    ##        4        5        5        7        8       10       11       12       12       14 
    ##   script     meta      img       br      pre   strong    tbody    table     code       li 
    ##       16       17       26       27       41       43       55       79      104      115 
    ##       tr        p       td      div        a     span 
    ##      127      150      268      358      371      423 
    
    # hadleyverse
    arrange(count(data_frame(tag=tags), tag), desc(n))
    
    ## Source: local data frame [36 x 2]
    ## 
    ##      tag   n
    ## 1   span 423
    ## 2      a 371
    ## 3    div 358
    ## 4     td 268
    ## 5      p 150
    ## 6     tr 127
    ## 7     li 115
    ## 8   code 104
    ## 9  table  79
    ## 10 tbody  55
    ## ..   ... ...
    

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 2021-05-05
      • 1970-01-01
      相关资源
      最近更新 更多