python - 我需要明确等待吗?

标签 python selenium webdriver selenium-webdriver

本质上,我遇到的情况是,当用户在 HTML 文本输入中键入内容时,元素会动态添加到页面中。添加元素不涉及任何网络事件。

我想在尽可能广泛的浏览器上运行我的测试 - 包括检查此行为,并将使用云服务,例如Saucelabs.com。

我想测试动态添加的元素数量是否正确。到目前为止我的测试:

text_input.send_keys('a') 
#send_keys('a') should make the browser immediately add an li to ul.new-elements
added_elements = browser.find_elements_by_css_selector('ul.new-elements li')
assert(len(added_elements), expected_num_of_list_items)

这在我的本地计算机上可靠地工作,但从我所看到的情况来看,它假设浏览器始终会在 Python/Webdriver 调用 find_elements_by_ 之前完成 DOM 操作。我认为这是一个危险的假设吗?

如果是这样,我需要明确等待吗?也许是这样的:

text_input.send_keys('a')
try:
    WebDriverWait(browser, 30).until(
        lambda b: len(b.find_elements_by_css_selector('ul.new-elements li')) == expected_num_of_list_items,
        'Timed out waiting for LI to be added.'
    )
except TimeoutException:
    fail('Timed out waiting for LI to be added.') #2 fail messages?

(我的理解是 implicit_wait 与这里无关)。

最佳答案

你的想法是正确的。一旦开始使用显式等待,您就应该忘记隐式等待。 here 提供了关于为什么不应混合使用这两种类型的精彩解释。 。

关于python - 我需要明确等待吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20202639/

相关文章:

python - 如何忽略 pandas.to_numeric() 中的错误并将 str 更改为 int

firefox - Selenium firefox 配置文件设置不正确

python - Firefox WebDriver 处理 "Download"窗口

javascript - 有条件地运行 it() block 或在 Webdriver.io 中嵌套 it() block

python - 合并从 csv 文件导入的 Dask 数据帧

python - App Engine Python 身份验证自定义重定向

python - 如何使用 if 语句来检查某些内容是否可见?

java - 如何在 PageObjects 模式中使用 WebDriver/Selenium 2 LoadComponents?

Python 临时文件模块和线程运行不佳;我究竟做错了什么?

ruby-on-rails - 有多少人将 Rspec 用于 Controller 和 View ?