【问题标题】:Selenium unable to locate and click a buttonSelenium 无法定位并单击按钮
【发布时间】:2021-09-02 04:20:58
【问题描述】:

我试图让我的脚本点击带有 WebDriverWait、XPath、Class 的结帐按钮,但它无论如何都不起作用:

HTML

<div class="confirm-container row">
    :before
    <div class="col-xs-12">
        <button class="btn btn-primary">
            <span>Effettua l'ordine</span>
        </button>
    </div>
    ::after
</div>

第一次尝试

var = '//*[@id="purchase-app"]/div/div[4]/div[1]/div[2]/div[5]/div/div/button'
WebDriverWait(web, 50).until(EC.element_to_be_clickable((By.XPATH, var)))
web.find_element_by_xpath(var).click()

第二次尝试 web.find_element_by_class_name('btn btn-primary').click()

第三次尝试 ActionChains(web).click(web.find_element_by_class_name('btn btn-primary')).perform()

【问题讨论】:

  • 我还没有对此进行过研究,但是当我试图让 selenium 按下 Youtube 中的订阅按钮之类的东西时它不起作用,我认为谷歌可能会让自动执行变得更加困难.虽然不确定

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


【解决方案1】:

当您使用Explicit wait 时,请尝试使用相对xpath

1st try 问题可以通过以下代码解决:

WebDriverWait(web, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Effettua l'ordine']/.."))).click()

2nd try web.find_element_by_class_name('btn btn-primary').click() - 类名不接受空格所以,请改用css selector

web.find_element_by_css_selector('button.btn.btn-primary').click()

第三次尝试时同样的问题。

更新 1:

问题是,您正在查看的按钮位于 iframe 中,因此您需要在交互之前切换它:

代码:

wait = WebDriverWait(driver, 10)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe[src^='/store/purchase?namespace']")))
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn.btn-primary"))).click()

进口:

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

【讨论】:

  • 我按照你说的做了调整,但还是不行
  • 错误是什么?以及您使用的是哪个代码?
  • 我收到的第一个代码是selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"button.btn.btn-primary"},第二个代码是selenium.common.exceptions.TimeoutException
  • 你能分享页面网址吗?
  • 这是Accedi con Xbox Live
【解决方案2】:

你可以试试这个

from selenium.webdriver import ActionChains
ActionChains(browser).click(element).perform()

而元素指的是开始标签和结束标签之间的任何东西。

如这里的答案所述:https://stackoverflow.com/a/61036237/11884764

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    相关资源
    最近更新 更多