【问题标题】:Wait for class to exist before continuing with selenium in Firefox在 Firefox 中继续使用 selenium 之前等待类存在
【发布时间】:2016-09-17 05:24:51
【问题描述】:

我正在尝试让 selenium 等到能够在页面上找到某个类,我尝试了几位代码但没有任何效果

尝试以下方法:

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

返回

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

尝试以下方法:

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

返回:

selenium.common.exceptions.InvalidSelectorException:消息:给定的选择器,但被选中,要么无效,要么不会产生 WebElement。发生以下错误: InvalidSelectorError:不允许复合类名

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

【问题讨论】:

    标签: python python-2.7 selenium


    【解决方案1】:

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

    请参阅以下示例。这个函数会等到你的类出现在 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")]'。 尝试其中一个,哪个更适合您。

    【讨论】:

    • 已编辑以表明这是错误的答案,用户应阅读下文以使用显式等待。
    【解决方案2】:

    你可以试试explicit-waits。这是一个小例子:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException
    
    
    def test(url):
        wait_for_element = 30  # wait timeout in seconds
        firefox = webdriver.Firefox()
        firefox.get(url)
    
        try:
            WebDriverWait(firefox, wait_for_element).until(
                EC.element_to_be_clickable((By.CLASS_NAME, "but selected'")))
        except TimeoutException as e:
            print("Wait Timed out")
            print(e)
    
    if __name__ == '__main__':
        test("http://www.python.org")
    

    【讨论】:

    • 这是正确答案,不是标记为正确的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 2018-06-10
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多