【问题标题】:Web scraping with R and rvest使用 R 和 rvest 进行网页抓取
【发布时间】:2015-09-06 09:55:06
【问题描述】:

我正在尝试使用 rvest 来学习使用 R 进行网页抓取。我正在尝试为页面的其他几个部分复制乐高示例,并使用 selector gadget 来标识。

我从R Studio tutorial 中提取了示例。使用下面的代码,1 和 2 有效,但 3 无效。

library(rvest)
lego_movie <- html("http://www.imdb.com/title/tt1490017/")

# 1 - Get rating
lego_movie %>% 
  html_node("strong span") %>%
  html_text() %>%
  as.numeric()

# 2 - Grab actor names
lego_movie %>%
  html_nodes("#titleCast .itemprop span") %>%
  html_text()

# 3 - Get Meta Score 
lego_movie %>% 
  html_node(".star-box-details a:nth-child(4)") %>%
  html_text() %>%
  as.numeric()

【问题讨论】:

    标签: r rvest


    【解决方案1】:

    我并没有真正了解所有管道和相关代码的速度,所以可能有一些新的方方正正的工具可以做到这一点......但鉴于上面的答案让你到达"83/100",你可以做点什么像这样:

    as.numeric(unlist(strsplit("83/100", "/")))[1]
    [1] 83
    

    我猜管道看起来像这样:

    lego_movie %>% 
      html_node(".star-box-details a:nth-child(4)") %>%
      html_text(trim=TRUE) %>%
      strsplit(., "/") %>%
      unlist(.) %>%
      as.numeric(.) %>% 
      head(., 1)
    
    [1] 83
    

    或者按照弗兰克的建议,您可以使用以下内容评估表达式 "83/100"

    lego_movie %>% 
      html_node(".star-box-details a:nth-child(4)") %>%
      html_text(trim=TRUE) %>%
      parse(text = .) %>%
      eval(.)
    [1] 0.83
    

    【讨论】:

      【解决方案2】:

      可以看到,在转换成数字之前,它返回了一个" 83/100\n"

      lego_movie %>% 
          html_node(".star-box-details a:nth-child(4)") %>%
           html_text() 
      # [1] " 83/100\n"
      

      您可以使用trim=TRUE 省略\n。您无法将其转换为数字,因为您有 /。 :

      lego_movie %>% 
           html_node(".star-box-details a:nth-child(4)") %>%
           html_text(trim=TRUE) 
      # [1] "83/100"
      

      如果您将其转换为数字,您将收到 NA 并带有警告,这并不意外:

      # [1] NA
      # Warning message:
      # In function_list[[k]](value) : NAs introduced by coercion
      

      如果您希望数字 83 作为最终答案,您可以使用 gsub 等正则表达式工具来删除 100\(假设所有电影的满分均为 100)。

      lego_movie %>% 
          html_node(".star-box-details a:nth-child(4)") %>%
           html_text(trim=TRUE) %>%
           gsub("100|\\/","",.)%>%
           as.numeric()
      # [1] 83
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-15
        • 1970-01-01
        • 2019-10-11
        • 1970-01-01
        相关资源
        最近更新 更多