所以我不熟悉网络抓取,并希望通过尝试抓住keurig网站获取乐趣,并提取有关某些k杯待售的信息来学习。我的目标是去k-cups页面,点击每个k-cup并提取一些信息,例如它是否含有咖啡因,烤肉颜色,还是原产地。我可以稍后解决这些问题,我在查找CSS或找到一种方法来自动化点击每个对象以获取额外信息的过程时遇到了麻烦。我这样做了:
library(rvest)
keurig <- read_html("http://www.keurig.com/beverages/k-cup-pods")
# Grab the CSS Nodes from the website
keurig.html <- html_nodes(keurig, ".keurig_card")
keurig.text <- html_text(keurig.html)
# Print the text
keurig.text
我最终得到了很多标签和新行字符,其中包含一些咖啡名称。我究竟如何抓取这些数据来获取每个k-cup的信息?
答案 0 :(得分:1)
使用此方法获取每个项目的链接:
library(rvest)
keurig <- read_html("http://www.keurig.com/beverages/k-cup-pods")
keurig.html <- html_nodes(keurig, ".product_name")
links = html_attr(keurig.html, name = "href")
包含指向每个项目的链接的类是product_name
。
获得节点后,提取href
属性。
结果(显示前四个):
[1] "/Beverages/Coffee/Regular/Breakfast-Blend-Coffee/p/Breakfast-Blend-Coffee-K-Cup-Green-Mountain"
[2] "/Beverages/Coffee/Regular/Dark-Magic%C2%AE-Extra-Bold-Coffee/p/Dark-Magic-Extra-Bold-Coffee-K-Cup-Green-Mountain"
[3] "/Beverages/Coffee/Regular/The-Original-Donut-Shop%C2%AE-Coffee/p/Original-Donut-Shop-Extra-Bold-Coffee-K-Cup-CP"
[4] "/Beverages/Coffee/Regular/Nantucket-Blend%C2%AE-Coffee/p/Nantucket-Blend-Coffee-K-Cup-Green-Mountain"
然后使用paste0
创建每个蛋糕详细信息页面的链接:
paste0("http://www.keurig.com/beverages/k-cup-pods",
"/Beverages/Coffee/Regular/Breakfast-Blend-Coffee/p/Breakfast-Blend-Coffee-K-Cup-Green-Mountain")