简体   繁体   English

如何让 selenium 单击网站弹出窗口上的按钮?

[英]How to get selenium to click a button on a website popup?

I'm trying to get selenium to click a button that's part of a popup.我正在尝试让 selenium 单击作为弹出窗口一部分的按钮。 I've tried just clicking the button like you normally would but it doesn't work.我试过像往常一样单击按钮,但它不起作用。 Here's the code:这是代码:

button = addButton = browser.find_element_by_id("button id")
button.click()

That wasn't working so I tried just clicking a coordinate but that doesn't seem to be working either:那不起作用,所以我尝试单击一个坐标,但这似乎也不起作用:

el = browser.find_elements_by_xpath("/html/body/div[5]")

action = webdriver.common.action_chains.ActionChains(browser)
action.move_to_element_with_offset(el, 1280, 735)
action.click()
action.perform()

Do I need my program to configure for the popup or something?我需要我的程序来配置弹出窗口还是什么? Im lost.我迷路了。

You need to wait for it to become clickable using Selenium's explicit wait:您需要使用 Selenium 的显式等待来等待它变为可点击:

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

wait = WebDriverWait(driver, 30)
wait.until(EC.element_to_be_clickable(
    (By.ID, "button id")))

Then just click it:然后只需单击它:

addButton = browser.find_element_by_id("button id")
addButton.click()

Also, your question lacks clarity about the nature of this popup.此外,您的问题对该弹出窗口的性质缺乏明确性。 If the above method won't work, there may be other options to use.如果上述方法不起作用,可能还有其他选项可以使用。

Your code:你的代码:

el = browser.find_elements_by_xpath("/html/body/div[5]")

action = webdriver.common.action_chains.ActionChains(browser)
action.move_to_element_with_offset(el, 1280, 735)

will not work for a few reasons: 1 You use find_elements_by_xpath for a single element.由于以下几个原因无法正常工作: 1 您将find_elements_by_xpath用于单个元素。 find_element_by_xpath have to be used.必须使用find_element_by_xpath 2 The path like this is very unlikely to be stable: /html/body/div[5] 3 Do not use coordinates unless it is strictly necessary. 2 像这样的路径不太可能是稳定的: /html/body/div[5] 3 除非绝对必要,否则不要使用坐标。 If you use such a method, it should use move_to_element如果你使用这样的方法,它应该使用move_to_element

from selenium.webdriver import ActionChains

locator = driver.find_element_by_xpath("some xpath")

actions = ActionChains(browser)
actions.move_to_element(locator)
actions.click().perform()

4 ActionChains is unlikely to be used in your case. 4 ActionChains 不太可能在您的情况下使用。 It is usually used for dropdowns and on hover elements.它通常用于下拉菜单和 hover 元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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