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

2024-10-01 11:20:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

<input placeholder="Search in your collabs" class="md-input" type="text">

我试图通过下面的代码选择它(在python):

^{pr2}$

但是在运行代码时,我得到了以下错误:

NoSuchElementException: Message: Unable to locate element: //input[@placeholder='Search in your collabs']

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

browser.switch_to_frame(browser.find_element_by_id("clb-iframe-workspace"));

但为什么现在不行了?在


Tags: to代码inbrowser元素网页inputsearch
1条回答
网友
1楼 · 发布于 2024-10-01 11:20:08

使用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']")))

如前所述here

相关问题 更多 >