【问题标题】:How to grab html_nodes for meta with itemprop equal to a certain value using rvest of tidyverse (Using R)如何使用 tidyverse 的 rvest(使用 R)获取 itemprop 等于某个值的元的 html_nodes
【发布时间】:2020-08-28 01:49:45
【问题描述】:
library(stringr);
library(rvest); 

denzel = read_html("https://www.imdb.com/filmosearch/?explore=title_type&role=nm0000243&ref_=filmo_ref_typ&sort=num_votes,desc&mode=detail&page=1&title_type=movie");

titles = denzel %>%
            html_nodes(".lister-item-header a") %>%
            html_text();

titles;

上面的代码获取了丹泽尔华盛顿的电影列表。 HTML 对象按预期工作。我得到了 50 部电影的字符串名称标题。

具体来说,我想解析对象中的以下子元素。

<meta itemprop="ratingValue" content="7.8" />
<meta itemprop="bestRating" content="10" />
<meta itemprop="ratingCount" content="383446" />

在上述情况下,我想为每个提取键和值...更具体地说,我知道键,所以我想获取关联的值...

meta = denzel %>%
    html_nodes("meta") %>%
    html_attr("itemprop");

meta;

这会返回部分内容,但不是我想要的。

下面的代码不起作用,是伪代码,

meta = denzel %>%
    html_nodes("meta") %>%
    html_attr("itemprop='ratingValue'");

理想情况下,meta(使用 html_node 或 html_nodes)会通过传入 itemprop 作为键来吐出内容属性值。

【问题讨论】:

    标签: r tidyverse rvest


    【解决方案1】:

    您可以使用rvest 提取数据,然后使用dplyr 进行一些数据操作可以帮助获得正确的格式。

    library(rvest)
    library(dplyr)
    
    data.frame(name = denzel %>% html_nodes("meta") %>% html_attr('itemprop'), 
               value = denzel %>% html_nodes("meta") %>% html_attr('content')) %>%
      filter(!is.na(name)) %>%
      mutate(movie_num = cumsum(name == 'ratingValue')) %>%
      tidyr::pivot_wider() %>%
      mutate(title = titles) %>%
      select(movie_num, title, everything()) %>%
      type.convert(as.is = TRUE)
    
    #   movie_num title             ratingValue bestRating ratingCount
    #       <int> <chr>                   <dbl>      <int>       <int>
    # 1         1 American Gangster         7.8         10      383451
    # 2         2 Training Day              7.7         10      381124
    # 3         3 Inside Man                7.6         10      331364
    # 4         4 The Equalizer             7.2         10      325088
    # 5         5 Man on Fire               7.7         10      323563
    # 6         6 Flight                    7.3         10      319627
    # 7         7 Deja Vu                   7           10      288497
    # 8         8 The Book of Eli           6.9         10      288067
    # 9         9 Philadelphia              7.7         10      219506
    #10        10 Safe House                6.7         10      202055
    # … with 40 more rows
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-13
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 2020-01-10
      • 2020-01-01
      • 2017-07-20
      • 1970-01-01
      相关资源
      最近更新 更多