Python webdriver is visible

Python Selenium click an element if visible

Assuming your xpath is correct, you should use click() , instead of click . It’s a method, not an attribute.

  • click is a method, it should be click()
  • Currently you are trying to click if the button is not displayed. It should be
if myelement.is_displayed(): driver.find_element_by_xpath("//a[@id='form1']").click() else: print (" ") 

You also don’t have to relocate the element to click on it

myelement = driver.find_element_by_xpath("//a[@id='form1']") if myelement.is_displayed(): myelement.click() else: print (" ") 

The best way to do it is by creating a base class and redefining click and find method and use this instead:

from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.select import Select from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from abc import abstractmethod class LocatorMode: XPATH = "xpath" CSS_SELECTOR = "cssSelector" NAME = "name" TAG_NAME = "tagName" class BasePage(object): def __init__(self, driver): self.driver = driver def wait_for_element_visibility(self, waitTime, locatorMode, Locator): element = None if locatorMode == LocatorMode.ID: element = WebDriverWait(self.driver, waitTime).\ until(EC.visibility_of_element_located((By.ID, Locator))) elif locatorMode == LocatorMode.NAME: element = WebDriverWait(self.driver, waitTime).\ until(EC.visibility_of_element_located((By.NAME, Locator))) elif locatorMode == LocatorMode.XPATH: element = WebDriverWait(self.driver, waitTime).\ until(EC.visibility_of_element_located((By.XPATH, Locator))) elif locatorMode == LocatorMode.CSS_SELECTOR: element = WebDriverWait(self.driver, waitTime).\ until(EC.visibility_of_element_located((By.CSS_SELECTOR, Locator))) else: raise Exception("Unsupported locator strategy.") return element def wait_until_element_clickable(self, waitTime, locatorMode, Locator): element = None if locatorMode == LocatorMode.ID: element = WebDriverWait(self.driver, waitTime).\ until(EC.element_to_be_clickable((By.ID, Locator))) elif locatorMode == LocatorMode.NAME: element = WebDriverWait(self.driver, waitTime).\ until(EC.element_to_be_clickable((By.NAME, Locator))) elif locatorMode == LocatorMode.XPATH: element = WebDriverWait(self.driver, waitTime).\ until(EC.element_to_be_clickable((By.XPATH, Locator))) elif locatorMode == LocatorMode.CSS_SELECTOR: element = WebDriverWait(self.driver, waitTime).\ until(EC.element_to_be_clickable((By.CSS_SELECTOR, Locator))) else: raise Exception("Unsupported locator strategy.") return element def find_element(self, locatorMode, Locator): element = None if locatorMode == LocatorMode.ID: element = self.driver.find_element_by_id(Locator) elif locatorMode == LocatorMode.NAME: element = self.driver.find_element_by_name(Locator) elif locatorMode == LocatorMode.XPATH: element = self.driver.find_element_by_xpath(Locator) elif locatorMode == LocatorMode.CSS_SELECTOR: element = self.driver.find_element_by_css_selector(Locator) else: raise Exception("Unsupported locator strategy.") return element def fill_out_field(self, locatorMode, Locator, text): self.find_element(locatorMode, Locator).clear() self.find_element(locatorMode, Locator).send_keys(text) def click(self, waitTime, locatorMode, Locator): self.wait_until_element_clickable(waitTime, locatorMode, Locator).click() 

Источник

How to check if element is visible in Selenium Python?

In this tutorial, you will learn how to check if a given element in the page is visible or not, using Selenium in Python.

To check if an element is visible in Selenium Python, get the element using a By strategy and locator string, and call the is_displayed() method on the element object. If the element is visible, then the function returns True, else it returns False.

We can use a Python if-else statement and the above expression as if-condition, as shown in the following.

if element.is_displayed(): print("The element is visible.") else: print("The element is not visible.")

Examples

1. Element is not visible

Consider the following HTML file. The div with id=»child3″ is hidden, meaning the div is not visible. On the other hand the other two divs with id=»child1″ and id=»child2″ are just normal and are visible.

  

Hello User!

This is child 1.
This is child 2.

Selenium Python - Check if element is visible - example input page

In the following program, we initialize a driver, then we load the index.html page running on our local server, or you may give the URL of the page you are interested in. Find the element with id=»child3″, and check if the element is visible or not using is_displayed() method of the element object.

Python Program

from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.common.by import By # Setup chrome driver service = ChromeService(executable_path=ChromeDriverManager().install()) driver = webdriver.Chrome(service=service) # Navigate to the url driver.get('http://127.0.0.1:5500/index.html') # Find an element by its ID element = driver.find_element(By.ID, 'child3') # check if the element is visible if element.is_displayed(): print("The element is visible.") else: print("The element is not visible.") # Close the driver driver.quit()

Selenium Python - Check if element is visible - example 1 output

2. Element is visible

In this example, we shall load the same HTML file as in the previous example. And we shall check if the element with id=»child2″ is visible or not.

Python Program

from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.common.by import By # Setup chrome driver service = ChromeService(executable_path=ChromeDriverManager().install()) driver = webdriver.Chrome(service=service) # Navigate to the url driver.get('http://127.0.0.1:5500/index.html') # Find an element by its ID element = driver.find_element(By.ID, 'child2') # check if the element is visible if element.is_displayed(): print("The element is visible.") else: print("The element is not visible.") # Close the driver driver.quit()

Selenium Python - Check if element is visible - example 2 output

3. Element is not visible by CSS

Consider the following HTML file. The div with id=»child1″ is hidden using CSS, meaning the div is not visible.

   #child1 

Hello User!

This is child 1.
This is child 2.

Element is hidden using CSS

In the following program, we check if the element with id=»child1″ is visible or not.

Python Program

from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.common.by import By # Setup chrome driver service = ChromeService(executable_path=ChromeDriverManager().install()) driver = webdriver.Chrome(service=service) # Navigate to the url driver.get('http://127.0.0.1:5500/index.html') # Find an element by its ID element = driver.find_element(By.ID, 'child1') # check if the element is visible if element.is_displayed(): print("The element is visible.") else: print("The element is not visible.") # Close the driver driver.quit()

Selenium Python - Check if element is visible - example 3 output

Summary

In this Python Selenium tutorial, we have given instructions on how to check if given element is visible or not in the webpage, with example programs.

Источник

Selenium Webdriver Python — Check if element is visible/detected/present [duplicate]

I want to check if an element is visible/present/detected by Selenium Web Driver for the following XPath:

//*[@data-animate-modal-popup="true"] 

Is there any Selenium’s function that returns TRUE or FALSE whenever that element is visible/present/detected? Last time I was using the following IF — Else

phone_number_invalid = driver.find_element_by_xpath('//*[@data-animate-modal-popup="true"]') if phone_number_invalid: code here . 

That find_element_by_xpath always throws an error whenever it doesn’t find the element. I want to only get TRUE or FALSE whenever the element is visible/present/detected. Thank you.

3 Answers 3

There is no native element to check if the element is present you can use :

create a function:

public boolean isElementPresent(By by) < try< driver.findElement(by); return true; >catch(NoSuchElementException e) < return false; >> 

and now call it in your if case:

 if(isElementPresent(By.xpath("//div[contains(text(),'Report name already exists. Please enter another name.')]"))) < //code >else if(isElementPresent(By.xpath("//div//span[contains(text(),'Grid Report saved successfully.')]"))) < //code >

Second option:

List element1 = driver.findElement(By.xpath("//div[contains(text(),'Report name already exists. Please enter another name.')]")); List element2 = driver.findElement(By.xpath("//div//span[contains(text(),'Grid Report saved successfully.')]")); if(element1.isEmpty() ) < //first set of code >else if(element2.isEmpty()) < //second set of code >

second option has more processing so first one is more recommended

  • Why don’t you use the extension for convenience.
  • With chrome:
  • Using «Xpath helper» for check elements:

For your problem, do you already have the element located or you need to check if the element is visible after certain action?

Use method is_displayed from the element. For example:

# you have located element and assign it to elem visibility = elem.is_displayed() print(visibility) # will print True or False 

Use fluent wait, and wrap it with a try except.

from selenium.common.exceptions import TimeoutException def check_visible_by_xpath(xpath, timeout=2): # Will actively search for the element in 2 seconds. # If found, return True and stop waiting. # If 2 seconds threshold reaches, return False (cannot find it visible in 2 seconds) try: element = WebDriverWait(driver, timeout).until( EC.visibility_of_element_located((By.XPATH, xpath))) return True except TimeoutException: return False # . # Some actions here type_in_phone_number() # Now you want to check, if after your previous action, something pops up?? visibility = check_visible_by_xpath('//*[@data-animate-modal-popup="true"]', 2) # check and do something about it if visibility: action_if_visible() else: action_if_not_visible() 

Источник

In python selenium, how does one find the visibility of an element?

I found the is_visible method in the Selenium documentation, but I have no idea how to use it. I keep getting errors such as is_visible needs a selenium instance as the first parameter . Also, what is a «locator»? Any help would be appreciated.

2 Answers 2

You should use is_displayed() instead:

from selenium import webdriver driver = webdriver.Firefox() driver.get('http://www.google.com') element = driver.find_element_by_id('gbqfba') #this element is visible if element.is_displayed(): print "Element found" else: print "Element not found" hidden_element = driver.find_element_by_name('oq') #this one is not if hidden_element.is_displayed(): print "Element found" else: print "Element not found" 

Visibility means that the element is not only displayed but also has a height and width that is greater than 0

visibility_of internally uses is_displayed() so I don’t see how your answer is different from the accepted answer. And OP is not asking how to wait for a condition to be met.

I did more than that, I looked at the implementation — visibility_of internally uses is_displayed() Click my link and you will understand.

@MikeScotty , let me clarify. is_displayed() will return Boolean condition is that element is displayed or not. That does not mean, you could use that element. e.g click(), get text and so on. For me, the best way is to use visibility_of_element_located cos Visibility means that the element is not only displayed but also has a height and width that is greater than 0. Which means, could interact with that element.

Will you please stop repeating the same stuff and just look at the code. visibility_of calls _element_if_visible which calls element.is_displayed() . It’s just 5 lines of code. I never said that is_displayed() does not rely on checking width/height of the element to determine the return value. Actually is_displayed() will execute this piece of JS — so it’s hard to tell what’s actually checked.

Источник

Читайте также:  Перезагрузить php fpm ubuntu
Оцените статью