If you’re using Selenium and need to click an (anchor) link, there are multiple ways to do it depending on how the link is structured. Let’s go through the different approaches:
1. Clicking a Link by Text
If you know the exact text of the link, use:
driver.find_element(By.LINK_TEXT, "Click Here").click()
This works only if the link text matches exactly.
2. Clicking a Link by Partial Text
If the text changes dynamically or you only know part of it, use:
driver.find_element(By.PARTIAL_LINK_TEXT, "Click").click()
This will click any link that contains "Click".
3. Clicking a Link Using XPath
If the link text isn’t reliable, target it with XPath:
driver.find_element(By.XPATH, "//a[@href='/target-page']").click()
This clicks an anchor tag with a specific href.
If the href is dynamic, match by text:
driver.find_element(By.XPATH, "//a[contains(text(), 'Learn More')]").click()
4. Clicking a Link Using CSS Selector
If the link has a unique class or ID, use CSS selectors:
driver.find_element(By.CSS_SELECTOR, "a.button-class").click()
This works best when there are multiple links and you need a specific one.
5. Handling JavaScript-Loaded Links
Some links aren’t traditional tags but JavaScript buttons. Try:
driver.execute_script("arguments[0].click();", element)
This forces a click using JavaScript.
Final Thoughts
The best approach depends on your webpage structure. If text is static, use LINK_TEXT. If not, XPath or CSS selectors are more reliable.