How to check if an object is visible on a web page using its xpath?

I use the RSelenium package in R to do webscraping. Sometimes after loading a web page, you need to check whether the object is visible on the web page 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 "exists"? The above code does not work as pseudo code. I also found code that works for checking objects using their "id", here it is:

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

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

+4
1

, , findElements(). , , , - "" :

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

, , 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")
}

, findElements(), findElement() NoSuchElement.

+2

Source: https://habr.com/ru/post/1618953/


All Articles