【发布时间】:2016-05-08 10:48:13
【问题描述】:
我有一个包含多个 HTML 链接的文件,现在想使用 dplyr 和 rvest 来获取每行每个链接的图像链接。
当我手动执行它时,它可以正常工作并返回该行,但是当在函数中调用相同的代码时,它会失败并出现以下错误:
错误:没有适用于 'xml_find_all' 的方法应用于 类“因素”
我不知道我做错了什么。任何帮助表示赞赏。为了让我的问题更清楚,我添加了(在 cmets 中)一些示例行,并展示了手动方法。
library(rvest)
library(dplyr)
library(httr) # contains function stop_for_status()
#get html links from file
#EXAMPLE
# "_id",url
# 560fc55c65818bee0b77ec33,http://www.seriouseats.com/recipes/2011/01/sriracha-ceviche-recipe.html
# 560fc57e65818bee0b78d8b7,http://www.seriouseats.com/recipes/2008/07/pasta-arugula-tomatoes-recipe.html
# 560fc57e65818bee0b78dcde,http://www.seriouseats.com/recipes/2007/08/cook-the-book-minty-boozy-chic.html
# 560fc57e65818bee0b78de93,http://www.seriouseats.com/recipes/2010/02/chipped-beef-gravy-on-toast-stew-on-a-shingle-recipe.html
# 560fc57e65818bee0b78dfe6,http://www.seriouseats.com/recipes/2011/05/dinner-tonight-quinoa-salad-with-lemon-cream.html
# 560fc58165818bee0b78e65e,http://www.seriouseats.com/recipes/2010/10/dinner-tonight-spicy-quinoa-salad-recipe.html
#
#load into SE
#
SE <- read.csv("~/Desktop/SeriousEats.csv")
#
#function to retrieve imgPath per URL
#using rvest
#
getImgPath <- function(x) {
imgPath <- x %>% html_nodes(".photo") %>% html_attr("src")
stop_for_status(res)
return(imgPath)
}
#This works fine
#UrlPage <- read_html ("http://www.seriouseats.com/recipes/2011/01/sriracha-ceviche-recipe.html")
#imgPath <- UrlPage %>% html_nodes(".photo") %>% html_attr("src")
#
#This throws an error msg
#
S <- mutate(SE, imgPath = getImgPath(SE$url))
【问题讨论】:
-
试试
mutate(SE, imgPath = getImgPath(url))。我认为通过使用$,当mutate期望逐行执行时,您正在引用整列 -
另外,请
dput你的SE对象(或至少一部分)。 -
网址是否被视为因素?在
read.csv命令中尝试stringsAsFactors=F? -
不。错误:没有适用于 'xml_find_all' 的方法应用于“字符”类的对象
-
你的
getImgPath()函数中的res是什么?我没有看到它在您的代码中的任何位置分配