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
To check the visibility of an element in a page, the method isDisplayed is used. It returns a Boolean value( true is returned if the element is visible, and otherwise false).
We can also confirm if an element is visible with the help of isDisplayed() method. This method returns a true or a false value. In case the element is invisible, the method returns a false value.
We can verify if an element does not exist in Selenium webdriver. To achieve this, we shall use the method getPageSource which gets the entire page source. So we can obtain a complete page source and check if the text of the element exists.
If you are using Chrome browser - one easy way you can use: Open the Inspect (or just click the F12 key) Mark the element you need and right click on it (or just right click on the object (the check box) you are looking for) Choose Copy ---> Copy Xpath.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With