8

I'm using the RSelenium package in R to do webscraping. Sometimes after loading a webpage, it's required to check if an object is visible in a webpage or not. For example:

library(RSelenium)

#open a browser
RSelenium::startServer()
remDr <- remoteDriver$new()
remDr <- remoteDriver(remoteServerAddr = "localhost" 
                  , port = 4444
                  , browserName = "firefox")
remDr$open()

remDr$navigate("https://www.google.com")
#xpath for Google logo
x_path="/html/body/div/div[5]/span/center/div[1]/img"

I need to do something like this:

if (exist(remDr$findElement(using='xpath',x_path))){
print("Logo Exists")
}

My question is what function should I use for "exist"? The above code does not work it's just a pseudo code. I have also found a code which works for checking objects using their "id", here it is:

remDr$executeScript("return document.getElementById('hplogo').hidden;", args = list())

The above code works for only "id", how should I do the same using "xpath"? Thanks

Mohammad
  • 1,078
  • 2
  • 18
  • 39

1 Answers1

7

To check if an element exists or not, use findElements() method. It would return an empty list if no element matching a locator found - an empty list is "falsy" by definition:

if (length(remDr$findElements(using='xpath', x_path))!=0) {
    print("Logo Exists")
}

To check if an element is visible, use isElementDisplayed():

webElems <- remDr$findElements(using='xpath', x_path)
if (webElems) {
    webElem <- webElems[0]
    if (webElem$isElementDisplayed()[[1]]) {
        print("Logo is visible")
    } else {
        print("Logo is present but not visible")
    }
} else {
    print("Logo is not present")
}

To check for presence, alternatively and instead of findElements(), you can use findElement() and handle NoSuchElement exception.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • thanks for your response. I tried to run your code which checks element existence and I get the following error: Error in if (remDr$findElements(using = "xpath", x_path)) { : argument is of length zero – Mohammad Dec 11 '15 at 00:16
  • I think I figured it out, I check the length of the list if it is zero, it was an empty list. – Mohammad Dec 11 '15 at 00:36
  • your second code for checking visibility is not working for me. I don't find the isElementDisplayed function in R? any suggestions? Thanks @alecxe – Mohammad Dec 11 '15 at 23:16
  • 1
    @Mohaa I've improved the example, hope that helps. I'm quite bad at R, forgive me if I have syntax errors in the code. The idea though should be clear. Take a look at an example `isElementDisplayed()` usage [here](http://stackoverflow.com/a/29433957/771848). – alecxe Dec 12 '15 at 01:25
  • This doesn't work with the current version I have now. RSelenium 3 on FF 52. – Peter.k Apr 21 '17 at 13:16