r - 使用 R 和 rvest 进行网页抓取

标签 r rvest

我正在尝试使用 rvest 来学习使用 R 进行网络抓取。我正在尝试为页面的其他几个部分复制 Lego 示例并使用 selector gadget到 id。

我从 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()

最佳答案

我并没有真正跟上所有管道和相关代码的速度,所以可能有一些新的狂热工具可以做到这一点......但考虑到上面的答案让你到达“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

或者如 Frank 所建议的,您可以使用类似以下内容计算表达式 "83/100":

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

关于r - 使用 R 和 rvest 进行网页抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30954686/

相关文章:

r - 找出ddply中数据源错误的原因

r - 内存分配 "Error: cannot allocate vector of size 75.1 Mb"

r - 使用 rvest,是否可以单击激活 div 并显示新内容以进行抓取的选项卡

r - 如何从 html 节点中删除 2-3 个元素并抓取其余元素?

r - 当达到空白值时 Purrr 函数编程错误

regex - 基于匹配其他列的部分字符串在数据框中创建新列

r - 如何选择列以使用 dplyr 中的中值函数?

r - 从数据框中聚合多列

r - 使用 Rvest 进行抓取时遇到问题

r - 在 R 和 rvest 中抓取多个链接的 HTML 表