使用Selenium时是否需要设置等待时间?

时间:2019-06-04 10:10:19

标签: python selenium css-selectors webdriverwait nosuchelementexception

有人说需要设置等待时间,否则可能会导致NoSuchElementException错误,因为页面未完成加载。

但是,我在低速网络(我限制了速度)上尝试了以下代码(没有任何等待线),并且登录过程仍然运行平稳(最初一直保持加载状态,当我取消限制时,加载立即完成,事情继续进行...)。

from selenium import webdriver
import json

# Get user info
with open('wjxlogin.json', encoding='utf-8') as fp_login:
    login = json.load(fp_login)
username = login['username']
password = login['password']

# First login
browser = webdriver.Firefox()
browser.get('https://www.wjx.cn/login.aspx')
browser.find_element_by_id('UserName').send_keys(username)
browser.find_element_by_id('Password').send_keys(password)
browser.find_element_by_id('RememberMe').click()
browser.find_element_by_id('LoginButton').click()

所以,我想知道当前的Selenium中是否存在自动等待模式,该模式不允许在最后一个过程完成之前执行下一行? 还是需要设置等待时间(例如在我的代码中)?

2 个答案:

答案 0 :(得分:2)

Selenium中的默认超时设置为 0 。这意味着Selenium将在页面完成加载且 DOM 中不存在特定元素后抛出NoSuchElementExpception。默认的 page 加载超时非常高(我认为是600秒),这就是为什么您尝试的操作不会在网络不好的情况下影响测试执行的原因。

但是-更改页面加载超时不会导致NoSuchElementException,而是会引发其他异常。如果您想尝试设置:

driver.set_page_load_timeout(3)

在速度有限的网络中,可能会给您带来一些失败。

当涉及到等待时-如您所见,您不需要它。仅在某些特定情况下才需要它-即动态内容被更新,用户交互加载了某些元素等。

答案 1 :(得分:0)

,根据最佳做法,您需要以WebDriverWait的形式设置等待时间,即{em> waiter ,并与{使用expected_conditions时使用{3}}。

您可以在以下位置找到相关的详细讨论:


此用例

根据您的用例,使用一组有效的凭据在How to sleep webdriver in python for milliseconds内登录,您可以使用以下解决方案:

  • 代码块:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC 
    
    options = webdriver.ChromeOptions() 
    driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get("https://www.wjx.cn/login.aspx")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.validate-input.user-name#UserName"))).send_keys("TheCoolestStacker")
    driver.find_element_by_css_selector("input#Password[name='Password']").send_keys("TheCoolestStacker")
    driver.find_element_by_css_selector("input#RememberMe[name='RememberMe']").click()
    driver.find_element_by_css_selector("input.submitbutton#LoginButton").click()
    
  • 浏览器快照:

website


NoSuchElementException

您可以在以下位置找到有关 NoSuchElementException 的一些详细讨论: