2

my goal is to use selenium python to click on this hyperlink element , here are the 3 solutions I have tried, none of them worked.

<div class="navigation_item">
<a href="javascript:;" onclick="navigationMenu('students');">Students (165)</a>
</div>

Solution 1:

driver.find_element_by_link_text('Students (165)').click()

error message: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"link text","selector":"Students (165)"}

Solution 2:

driver.find_element_by_xpath('/html/body/div[2]/div[1]/div[3]/div/div[1]/div[3]/div[7]/a').click()

error message: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[2]/div[1]/div[3]/div/div[1]/div[3]/div[7]/a"}

Solution 3:use javascript code

javascript = "document.getElementsByClassName('navigation_item')[3].click();"
driver.execute_script(javascript)

error message:selenium.common.exceptions.JavascriptException: Message: javascript error: Cannot read property 'click' of undefined

So, what went wrong with each solution? How can I make it work?

Guy
  • 46,488
  • 10
  • 44
  • 88

2 Answers2

0

To click on the element with text as Students (165) you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using LINK_TEXT:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Students (165)"))).click()
    
  • Using PARTIAL_LINK_TEXT:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "Students ("))).click()
    
  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.navigation_item>a[onclick^='navigationMenu'][onclick*='students']"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='navigation_item']/a[starts-with(@onclick, 'navigationMenu') and contains(., 'Students')]"))).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
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
-1

It probably throws an error because page isn't loaded when you're checking for element. Try using:

browser = webdriver.Firefox()

browser.implicitly_wait(5)

Then you can use your first solution: driver.find_element_by_link_text('Students (165)').click()

This should be triggered on find element setting timeout for 5 seconds.

viciousP
  • 510
  • 3
  • 14