I have this RSelenium
script:
library(tidyverse)
library(RSelenium) # running through docker
library(rvest)
library(httr)
remDr <- remoteDriver(port = 4445L, browserName = "chrome")
remDr$open()
remDr$navigate("https://books.google.com/")
books <- remDr$findElement(using = "css", "[name = 'q']")
books$sendKeysToElement(list("NHL teams", key = "enter"))
bookElem <- remDr$findElements(using = "xpath",
"//h3[@class = 'LC20lb']//parent::a")
links <- sapply(bookElem, function(bookElem){
bookElem$getElementAttribute("href")
})
The above clicks every link on the Google search return (there are 10 per page). The books that I search mostly have a preview once you click into it. If there's a preview, there's a small About this book
link to click on that brings you to the publishing info.
I want to click on the first links, and then if there's a preview, click on "About this book." I have the below, but I just get Error: object of type 'closure' is not subsettable
errors:
for(link in links) {
# Navigate to each link
remDr$navigate(link)
# If statement to get past book previews
if (str_detect(link, "frontcover")) {
link2 <- remDr$findElement(using = 'xpath',
'//*[@id="sidebar-atblink"]//parent::a')
link2 <- as.list(link2)
print(class(link2))
link2_about <- sapply(link2, function(ugh){
ugh$getElementAttribute('href')
})
} else {
print("nice going, dumbass")
}
}
Or I try a for
loop instead of a the sapply
, I get Error: $ operator is invalid for atomic vectors
:
for(link in links) {
# Navigate to each link
remDr$navigate(link)
# If statement to get past book previews
if (str_detect(link, "frontcover")) {
link2 <- remDr$findElement(using = 'xpath',
'//a[@id="sidebar-atb-link" and span[.="About this book"]]')
for(i in length(link2)){
i$getElementAttribute('href')
}
} else {
print("dumbass")
}
}
How can I successfully click into that second link, depending on if the preview is there? Thanks!