1

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()
2
  • 2
    Show how you tried. Share code Commented Nov 12, 2020 at 11:18
  • there ya go @JaSON Commented Nov 12, 2020 at 11:51

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

2 Comments

I get this error with both methods NoSuchElementException
@chronovirus what if to put driver.implicitly_wait(10) before searching for element?
0

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
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.