【问题标题】:click on anchor tag having href = '#'单击具有 href = '#' 的锚标记
【发布时间】:2018-05-10 10:16:50
【问题描述】:

我在下面使用 selenium 的 python 代码。单击不适用于具有 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()  

这是我正在使用的网页 html 代码。

<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>

【问题讨论】:

  • 给出你想要重定向页面的链接而不是“#”..
  • 那些是不存在的链接,你必须在href属性中提供html文件的位置

标签: python python-3.x selenium selenium-webdriver selenium-chromedriver


【解决方案1】:

根据您共享的 HTML,似乎 AUT 是基于 JavaScript,因此单击带有文本的链接作为 验证数据 您必须诱导 WebDriverWait 元素才能被点击,并且您可以使用以下任一选项:

  • 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()
    

注意:您将需要以下导入:

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

【讨论】:

【解决方案2】:

尝试使用 javascript 执行器来单击您的元素。

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

上面的代码需要适应python(我不熟悉,但你明白了)

希望对你有帮助

【讨论】:

  • 我现在收到此错误:selenium.common.exceptions.WebDriverException:消息:未知错误:元素 ... 在点 (88, 460) 不可点击。其他元素会收到点击:
    ...
猜你喜欢
  • 2021-01-03
  • 1970-01-01
  • 2023-03-31
  • 2013-07-14
  • 2015-09-23
  • 2020-10-13
  • 2021-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多