在 Firefox 中继续使用 selenium 之前等待类存在 [英] Wait for class to exist before continuing with selenium in Firefox

查看:45
本文介绍了在 Firefox 中继续使用 selenium 之前等待类存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让 selenium 等到某个类能够在页面上找到,我已经尝试了一些代码,但没有任何效果

I'm trying to make selenium wait until a certain class is able to be found on a page, I've tried several bits of code but nothing is working

尝试以下操作:

while not firefox.find_element_by_css_selector('.but selected'):
    print "test"
    time.sleep(1)

退货

selenium.common.exceptions.NoSuchElementException:消息:无法定位元素

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element

尝试以下操作:

while not firefox.find_element_by_class_name('but selected'):
    print "test"
    time.sleep(1)

返回:

selenium.common.exceptions.InvalidSelectorException: 消息:给定的选择器但已选择无效或不会导致 WebElement.出现以下错误:InvalidSelectorError: 不允许复合类名

selenium.common.exceptions.InvalidSelectorException: Message: The given selector but selected is either invalid or does not result in a WebElement. The following error occurred: InvalidSelectorError: Compound class names not permitted

知道我做错了什么以及如何解决吗?

Any idea what I am doing wrong and how to fix it?

推荐答案

注意:正确答案是下面使用显式等待的答案.

请参阅以下示例.此函数将等到您的类出现在 DOM 中.

See the following example. This function will wait till your class appears in DOM.

import time
...
...
def wait_for_class_to_be_available(browser, total_wait=100):
    try:
        # Give only one class name, if you want to check multiple classes then 'and' will be use in XPATH
        # e.g //*[contains(@class, "class_name") and contains(@class, "second_class_name")]
        elem = browser.find_element_by_xpath('//*[contains(@class, "class_name")]')
    except:
        total_wait -= 1
        time.sleep(1)
        if total_wait > 1: wait_for_class_to_be_available(browser, total_wait)

您还可以将 xpath 更改为 '//xpath/to/that/element[contains(@class, "class_name")]'.尝试其中一种,以更适合您的为准.

You can also change the xpath to '//xpath/to/that/element[contains(@class, "class_name")]'. Try one of them, whichever is more suitable to you.

这篇关于在 Firefox 中继续使用 selenium 之前等待类存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆