如何将向量元素作为单个参数传递给R中的函数
我正在使用rvest进行一个web抓取项目如何将向量元素作为单个参数传递给R中的函数,r,R,我正在使用rvest进行一个web抓取项目 html_text(html_nodes(url, CSS)) 从url中提取数据,只要找到匹配的CSS。我的问题是,我正在抓取的网站对每个列出的产品都使用了唯一的CSS ID(例如ListItem\u 001\u Price)。因此,1CSS精确定义了1个商品的价格,因此自动化的网页垃圾处理不起作用 我可以创建一个向量 V <- c("ListItem_001_Price", "ListItem_002_Price", "ListItem_
html_text(html_nodes(url, CSS))
从url
中提取数据,只要找到匹配的CSS
。我的问题是,我正在抓取的网站对每个列出的产品都使用了唯一的CSS ID
(例如ListItem\u 001\u Price
)。因此,1CSS
精确定义了1个商品的价格,因此自动化的网页垃圾处理不起作用
我可以创建一个向量
V <- c("ListItem_001_Price", "ListItem_002_Price", "ListItem_003_Price")
V您可以在此处尝试使用lappy
:
V <- c("ListItem_001_Price", "ListItem_002_Price", "ListItem_003_Price")
results <- lapply(V, function(x) html_text(html_nodes(url, x)))
Vhtml\u nodes()
需要首字母“.”才能按css类查找标记。您可以手动创建
V谢谢蒂姆,它工作得很好!应用程序中的“函数(x)”是我无法理解的——很高兴看到它正常工作。很好的解释,伙计,从你的博文中学到了很多!感谢您在这里分享其他功能。
library(rvest)
# An example piece of html
example_markup <- "<ul>
<li class=\"ListItem_041_Price\">Brush</li>
<li class=\"ListItem_031_Price\">Phone</li>
<li class=\"ListItem_002_Price\">Paper clip</li>
<li class=\"ListItem_012_Price\">Bucket</li>
</ul>"
html <- read_html(example_markup)
# Avoid manual creation of css with regex
regex <- 'ListItem_([0-9]{3})_Price'
# Note that ([0-9]{3}) will match three consecutive numeric characters
price_classes <- regmatches(example_markup, gregexpr(regex, example_markup))[[1]]
# Paste leading "." so that html_nodes() can find the class:
price_classes <- paste(".", price_classes, sep="")
# A singel entry is found like so:
html %>% html_nodes(".ListItem_031_Price") %>% html_text()
# Use sapply to get a named character vector of your products
# Note how ".ListItem_031_Price" from the line above is replaced by x
# which will be each item of price_classes in turn.
products <- sapply(price_classes, function(x) html %>% html_nodes(x) %>% html_text())