为什么我在 selenium 中找不到带有占位符的输入元素?

Ale*_*lex 6 python selenium

在网页中,我有以下元素:

<input placeholder="Search in your collabs" class="md-input" type="text">
Run Code Online (Sandbox Code Playgroud)

我尝试通过以下代码段(在python)中选择:

elem = browser.find_element_by_xpath("//input[@placeholder='Search in your collabs']")
Run Code Online (Sandbox Code Playgroud)

但是在运行代码时出现以下错误:

NoSuchElementException: Message: Unable to locate element: //input[@placeholder='Search in your collabs']
Run Code Online (Sandbox Code Playgroud)

我正在寻找的元素在我之前正确选择的 iframe 内(我find_element_by_xpath之前用其他一些属性做了另一个)。详细来说,我之前做的是:

browser.switch_to_frame(browser.find_element_by_id("clb-iframe-workspace"));
Run Code Online (Sandbox Code Playgroud)

那么,为什么这现在不起作用呢?

Wür*_*paß 7

使用sleep(如您的评论中提到的)是一个糟糕的解决方案,因为它不可避免地会减慢您的测试执行速度,并且可能会日复一日地失败。更好的解决方案是使用超时。超时会等待指定的时间跨度,但会尽快继续(即满足您的预期条件)。

您应该增加定位元素的隐式等待超时或使用显式等待,例如

from selenium.webdriver.support import expected_conditions as expect
....
//wait up to 120sec, poll every sec
elem = WebDriverWait(browser, 120, 1).until(
        expect.visibility_of_element_located(
        (By.XPATH, "//input[@placeholder='Search in your collabs']")))
Run Code Online (Sandbox Code Playgroud)

正如这里所解释的