Home > front end >  How do I get the onclick href="#" in python selenium
How do I get the onclick href="#" in python selenium

Time:10-12

<a href="#" onclick="showZone("gaoland.net")">gaoland.net</a>

I want to click on the link from onclick.

I am using python selenium. Thanks

I have already tested all this but without success

browser.find_element_by_xpath('//href[text()="gaoland.net"]').click()
browser.find_element_by_xpath('//a[@href="#"]').click()
browser.find_element_by_xpath('//a[contains(@href,"#")]').click()
browser.find_element_by_xpath("//a[contains(@onclick, "'showZone("gaoland.net")'")]").click()
browser.find_element_by_partial_link_text("gaoland.net"  Keys.RETURN)
browser.find_element_by_xpath("//a[con**strong text**tains(@onclick, '#')]").click()
browser.find_element_by_xpath('//a[contains(@href,"showZone("gaoland.net")")]').click()
browser.find_element_by_partial_link_text('showZone("gaoland.net")').click()
browser.find_element_by_xpath('//a[contains(@onclick="showZone("gaoland.net")]').click()

CodePudding user response:

Preferred way is LINK_TEXT:

browser.find_element_by_link_text('gaoland.net').click()

or with WebDriverWait :

 WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "gaoland.net"))).click()

Imports :

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

if that does not work, please try xpath or css selector :

  1. xpath :

    //a[contains(@onclick,'showZone') and text()='gaoland.net']
    

or

//a[contains(@onclick,'showZone')]

css would be :

a[onclick^='showZone']

You can use either use driver.find_element_by_xpath('') or

WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@onclick,'showZone')]"))).click()

PS : Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.

  • Related