故障查找按钮

时间:2018-12-31 22:35:43

标签: python selenium

我遇到硒问题,不想找到按钮。我使用的代码可以在同一网站上的先前按钮上使用,但是由于某种原因,它很难找到该按钮。

这是HTML:

<button id="getCoupon" class="getCoupon" onclick="IWant()" style="" data-i18n="view_prod_get_coupon">Get Your Coupon</button>

这是我到目前为止尝试过的:

driver.find_element_by_id('getCoupon').click()
driver.find_element_by_xpath('//*[@id="getCoupon"]').click()
driver.find_element_by_class_name('getCoupon').click()

以下是最后两个的错误: 尝试使用XPath:

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="getCoupon"]"}

尝试使用类名:

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"class name","selector":"getCoupon"}

2 个答案:

答案 0 :(得分:1)

您的定位器似乎很好,因为您的元素未按时加载,可能正在执行并且执行速度很快。您可以尝试使用显式等待

// wait for element present 

element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "getCoupon"))
element.click()

// wait until element get visible

element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "getCoupon"))
element.click()

出于调试目的,您还可以使用

之类的方法
element = driver.find_element_by_id('getCoupon')

if element.is_displayed():
    element.click()
else:
    print ("element not visible ")

不要忘记导入所需的软件包。有关更多信息,请参考this

答案 1 :(得分:0)

尝试查看html代码。我认为可能是:

  1. 此按钮可能在框架中,然后您需要先切换到框架然后找到按钮。

  2. 也许它是由javascript生成的,所以您需要等到它将由js代码生成。

相关问题