首页 > 解决方案 > Cabela 使用 rvest 的基于 R 的 Web Scraper

问题描述

也许有点不寻常,但我想追查我有兴趣购买的特定步枪。我熟悉 R,所以我开始走这条路,但我猜还有更好的选择。

我想做的是每小时检查一次网页,看看可用性是否发生了变化。如果有,我会收到一条短信。

我开始使用 rvest 和 twilio。问题是我无法弄清楚如何一直到我需要的数据。该页面有一个“添加到购物车”按钮,如果使用 css 样式 display:none 无法使用该项目,则该按钮不会显示。

我尝试了各种方法来尝试通过使用 id 名称、css 类、xpath 等来了解特定的 div,但一直没有找到任何结果。

有任何想法吗?是 div 名称的格式吗?还是我必须手动挖掘每个嵌套的 div?

编辑:我能够找到正确的 xpath 来工作。但正如下面所指出的,您看不到样式。

EDIT2 - 在缺货 div 中,显示文本“仅在选择商店中”,但我不知道如何隔离它。

#Schedule script to run every hour

library(rvest)
library(twilio)

#vars for sms
Sys.setenv(TWILIO_SID = "xxxxxxxxxxx")
Sys.setenv(TWILIO_TOKEN = "xxxxxxxxxxx")

#example, two url's - one with in stock item, one without
OutStockURL <- read_html("https://www.cabelas.com/shop/en/marlin-1895sbl-lever-action-rifle?searchTerm=1895%20sbl")
InStockURL <- read_html("https://www.cabelas.com/shop/en/thompson-center-venture-ii-bolt-action-centerfire-rifle")

#div id that contains information on if product is in stock or not
instockdivid <- "WC_Sku_List_TableContent_3074457345620110138_Price &amp; Availability_1_16_grid"
outstockdivid <- "WC_Sku_List_TableContent_24936_Price &amp; Availability_1_15_grid"

#inside the div is a button that is either displayed or not based on availability
instockbutton <- 'id="SKU_List_Widget_Add2CartButton_3074457345620110857_table"'
outstockbutton <- 'id="SKU_List_Widget_Add2CartButton_3074457345617539137_table"'

#if item is unavailable, button style is set to display:none - style="display: none;"

test <- InStockURL %>%
  html_nodes("div")

#xpath to buttons
test <- InStockURL %>%
html_nodes(xpath = '//* 
[@id="SKU_List_Widget_Add2CartButton_3074457345620110857_table"]')

test2 <- OutStockURL %>%
html_nodes(xpath = '//* 
[@id="SKU_List_Widget_Add2CartButton_3074457345617539137_table"]')

#not sure where to go from here to see if the button is visible or not

#if button is displayed, send email
tw_send_message(
  to = "+15555555555",
  from = "+5555555555",
  body = paste("Your Item Is Available!")
)

标签: rweb-scrapingrvest

解决方案


推荐阅读