如何使用 rvest 从 IMDB 中获取电影的预算值

How to scrape the budget value of a movie from IMDB using rvest

我曾尝试使用 rvest 包从 IMDB.com 中获取总值和预算值,但我做不到。我的代码是:

library(rvest)    
movie <- html("http://www.imdb.com/title/tt1490017/")   
movie %>% 
html_node("#budget .itemprop") %>%     
html_text() %>%      
as.numeric()

然后我得到

numeric(0)

您可以这样获取预算值:

library(tidyr) # for extract_numeric
library(rvest)
movie <- read_html("http://www.imdb.com/title/tt1490017/")
movie %>%
html_nodes("#titleDetails :nth-child(11)") %>%     
  html_text() %>%      
  extract_numeric()

[1] 6e+07

您的示例与 rvest package vignette. That vignette suggests you use SelectorGadget 中的示例相似,我曾在该示例中找到 CSS 选择器 return 只有 Budget 元素。要查看该元素,运行 除了本系列的最后一条管道线之外的所有元素,您就会明白为什么我选择使用 tidyr 中的 extract_numeric 来解析它。

您需要 rvest 到 运行 的最新版本,因为我正在使用 read_html() 函数,它已替换您示例中使用的 html() .

Sam Firke 提供了一个非常巧妙的解决方案。我只是 post 我想展示一个不同的方法来提取数值。作为 Sam Firke,我使用了 SelectorGadgethtml 函数似乎工作正常。我使用了 gsub:

而不是 tidyr,我不知道它有这么方便的功能
library(rvest)    
movie <- html("http://www.imdb.com/title/tt1490017/") 
movie %>% 
  html_node(".txt-block:nth-child(11)") %>%
  html_text() %>% 
  gsub("\D", "", .) %>% 
  as.numeric()

输出:

[1] 6e+07