chronovirus
chronovirus

Reputation: 41

How to click an element using Selenium Python

So I have this element in HTML...

<a href="#" onclick="on_catolog(2);"><span style="font-size:11pt">Security</span></a>

... and I want to click it using Selenium in python. How can I do it? (Maybe I can identify it using onclick, but how?)

Also, here is what I've tried:

security = driver.find_element_by_xpath("//button[@onclick=\"on_catolog(2);\"]")
security.click()

Upvotes: 1

Views: 63

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193058

To click on the element with text as Security you can use either of the following Locator Strategies:

  • Using css_selector:

    driver.find_element_by_css_selector("a[onclick^='on_catolog'] > span[style='font-size:11pt']").click()
    
  • Using xpath:

    driver.find_element_by_xpath("//a[starts-with(@onclick, 'on_catolog')]/span[text()='Security']").click()
    

Ideally, to click on the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[onclick^='on_catolog'] > span[style='font-size:11pt']"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[starts-with(@onclick, 'on_catolog')]/span[text()='Security']"))).click()
    
  • Note: You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

Upvotes: 0

JaSON
JaSON

Reputation: 4869

You used wrong tag name in your XPath "//button[@onclick=\"on_catolog(2);\"]". It's not a button, but anchor tag. Try

"//a[@onclick='on_catolog(2);']"

Or click by link text:

security = driver.find_element_by_link_text("Security")
security.click()

Upvotes: 1

Related Questions