简体   繁体   中英

click on anchor tag having href = '#'

I am using below python code using selenium. click is not working on anchor tag having href = "#"

import time    
import unittest   
from selenium import webdriver   
from selenium.webdriver.common.by import By   
from selenium.webdriver.support.ui import Select   
from selenium.webdriver.common.keys import Keys   

driver = webdriver.Chrome("E:\chromedriver.exe")   
driver.get('file:///E:/Selenium/validateTest.html')     

driver.find_element_by_xpath("//a[@id='validateData']/i[text()=' Validate Data']").click()  

Here is the web html code that I am using.

 <h1>Anchor tag</h1> <a href="#" class="button js-button" role="button">Show content</a> <a href="#" id="validateData" class="btn btn-red" onclick="document.write(5 + 6)"><i class="fa fa-binoculars" aria-hidden="true"></i> Validate Data</a> 

Try using a javascript executor to click your element.

JavascriptExecutor js = (JavascriptExecutor) driver; 
WebElement elementToClick = driver.find_element_by_xpath("//a[@id='validateData']/i[text()=' Validate Data']");
js.executeScript("arguments[0].click();", elementToClick);

Above code needs to be adapted to python ( which i'm not familiar with, but you get the idea)

Hope this helps

As per the HTML you have shared it seems the AUT is based on JavaScript , so to click on the link with text as Validate Data you have to induce WebDriverWait for the element to be clickable and you can use either of the following options :

  • LINK_TEXT :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Validate Data"))).click() 
  • CSS_SELECTOR :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.btn.btn-red#validateData"))).click() 
  • XPATH :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='btn btn-red' and @id='validateData']"))).click() 

Note : You will require 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM