0

I am planning to buy an iPad, but it only comes in stock for a few minutes and runs out again. So I wrote a R script to check the availability that triggers an email when it is available on amazon.

I am running this script on a R studio server and have scheduled it to run every 1 minute using cronR.

library(xml2)
library(rvest)
library(mailR)
library(stringr)

rm(list=ls())

link <- "https://www.amazon.in/dp/B0864JWYQX/" #iPad

ipad <- read_html(link)

#Availability 
avail <- ipad %>%
  html_nodes("#availability .a-size-medium") %>%
  html_text() %>%
  str_remove_all("\\\n")

#item name
item <- ipad %>%
  html_node("#productTitle") %>%
  html_text() %>%
  str_remove_all("\\\n")

if (avail == "Currently unavailable.") {
  print(paste("Unavailable on",Sys.time()))
} else {
  sender <- "Ashwini Kalantri <my@email.com>"
  to <- c("Ashwini Kalantri <my@email.com>","trigger@applet.ifttt.com")
  body <- paste0("<p>",item," is available on ",
                 format(Sys.time(),"%d %B %Y %I:%M %p"),
                 ".</p><p><a href =",quote("https://www.amazon.in/dp/B0864JWYQX/"),">BUY NOW!</a></p>")
  send.mail(from = sender,
            to = to,
            subject = paste0(item," #ipad"),
            body = body,
            html = T,
            smtp = list(host.name = "smtp.gmail.com", port = 465, 
                        user.name = "my@email.com",            
                        passwd = "password", ssl = TRUE),
            authenticate = TRUE,
            send = TRUE)
}

For the first day the script ran fine without any errors. But then I started getting the following error in the log file. This is random, sometimes the script would run perfectly as desired but other times it would give the error below. The script runs as desired every time, when I run it in the R studio console.

Error in if (avail == "Currently unavailable.") { : 
  argument is of length zero
Execution halted

I don't know what is wrong. Would appreciate help.

r2evans
  • 141,215
  • 6
  • 77
  • 149
  • 1
    Put a `print(paste("avail is", avail))` immediately in front of the `if` statement. You'll soon see what the problem is. The clue is in the error message. – Limey Jul 08 '20 at 05:06
  • It seems to be blank. Why should that be? `[1] "avail is " Error in if (avail == "Currently unavailable.") { : argument is of length zero Execution halted` – Ashwini Kalantri Jul 08 '20 at 05:50
  • It seems that Amazon is blocking the web scraping requests. `{html_document} [1] \n – Ashwini Kalantri Jul 08 '20 at 06:11

0 Answers0