Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Selenium click an element if visible

Using Python Selenium I am trying to check if an element is visible and then click it if it is...

# Check to see if element is visible
    myelement = driver.find_element_by_xpath("//a[@id='form1']")

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

This isn't working, where am I going wrong?

like image 947
fightstarr20 Avatar asked Oct 29 '25 22:10

fightstarr20


2 Answers

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

like image 188
Gustavo Bezerra Avatar answered Oct 31 '25 10:10

Gustavo Bezerra


You have two problems

  • 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 (" ")
like image 32
Guy Avatar answered Oct 31 '25 12:10

Guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!