【问题标题】:rvest & parsing HTML: find a list of items, and extract specific information from each itemrvest & 解析 HTML:查找项目列表,并从每个项目中提取特定信息
【发布时间】:2017-03-15 19:43:23
【问题描述】:

我正在努力寻找简洁的代码来执行以下操作:

  • 查找包含五个项目的列表
  • 遍历所有五个项目
  • 从每个项目中提取 4 列
  • 返回一个包含五行的数据框,每行一个。

示例 HTML:

<div class="i-am-a-list">
    <div class="item item-one"><a href=""></a><a class="title"></a><p>sub-title</p></div>
    <div class="item item-two"><a href=""></a><a class="title-two"></a><p>sub-title</p></div>
    <div class="item item-three"><a href=""></a><a class="title-three"></a><p>sub-title</p></div>
    <div class="item item-four"><a href=""></a><a class="title-for"></a><p>sub-title</p></div>
    <div class="item item-five"><a href=""></a><a class="title-five"></a><p>sub-title</p></div>

</div>

到目前为止的代码:

# find the upper list   
coll <- read_html(doc.html) %>%
  html_node('.i-am-a-list') %>%
  html_nodes(".item")

# problems here, how do I iterate over the returned divs 
# I was expecting something like
results <- coll %>% 
    do(parse_a_single_item) %>%
    rbind_all()

是否有可能编写如此漂亮的代码来完成如此常见的任务? :)

【问题讨论】:

    标签: html r dplyr rvest


    【解决方案1】:

    这不是很漂亮,我觉得我错过了一些明显的方法,但你可以这样做:

    library(rvest)
    library(purrr)
    
    read_html(x) %>%
      html_node('.i-am-a-list') %>%
      html_nodes(".item") %>% 
      map_df(~{
        class = html_attr(.x, 'class')
        a1 = html_nodes(.x, 'a') %>% '['(1) %>% html_attr('href')
        a2 = html_nodes(.x, 'a') %>% '['(2) %>% html_attr('class')
        # or with CSS selector
        # a1 = html_nodes(.x, 'a:first-child') %>% html_attr('href')
        # a2 = html_nodes(.x, 'a:nth-child(2)') %>% html_attr('class')
        p = html_nodes(.x, 'p') %>% html_text()
        data.frame(class, a1, a2, p)
        })
    
    #             class a1          a2         p
    # 1   item item-one          title sub-title
    # 2   item item-two      title-two sub-title
    # 3 item item-three    title-three sub-title
    # 4  item item-four      title-for sub-title
    # 5  item item-five     title-five sub-title
    

    数据:

    x <- '<div class="i-am-a-list">
      <div class="item item-one"><a href=""></a><a class="title"></a><p>sub-title</p></div>
      <div class="item item-two"><a href=""></a><a class="title-two"></a><p>sub-title</p></div>
      <div class="item item-three"><a href=""></a><a class="title-three"></a><p>sub-title</p></div>
      <div class="item item-four"><a href=""></a><a class="title-for"></a><p>sub-title</p></div>
      <div class="item item-five"><a href=""></a><a class="title-five"></a><p>sub-title</p></div>
    </div>'
    

    【讨论】:

    • 这是一个很好的方法。 cld 使用 CSS vs [ 定位每个锚标签,但除此之外它是一个 ++gd 解决方案
    • 先生,这已经非常棒了。甚至在我完成我的漂亮得多的代码之前。欣赏!
    猜你喜欢
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    相关资源
    最近更新 更多