美文网首页
38 selenium三种等待方式

38 selenium三种等待方式

作者: 薛东弗斯 | 来源:发表于2024-03-18 06:05 被阅读0次

    time.sleep()

    import time
    
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    
    driver = webdriver.Chrome()
    driver.maximize_window()
    # 等待3秒,整个页面加载不完成,报超时异常
    # driver.set_page_load_timeout(3)   # 设置等待时间,超时则报异常
    driver.implicitly_wait(0.01)
    driver.get("https://www.baidu.com")
    driver.find_element(By.ID,'kw').send_keys("Selenium")
    time.sleep(3)    # 强制等待,一般不建议使用
    driver.close()
    

    implicitly_wait

    import os
    import time
    
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    
    from utils.get_filepath import download_file_path
    
    path = download_file_path() + "/LATEST_RELEASE"
    if os.path.exists(path):
        print("文件存在")
        os.remove(path)
        print("文件已删除")
    
    chromeOptions = webdriver.ChromeOptions()
    prefs = {"download.default_directory": "{}".format(download_file_path())}
    chromeOptions.add_experimental_option("prefs", prefs)
    driver = webdriver.Chrome(chromeOptions)
    driver.implicitly_wait(1)
    driver.maximize_window()
    driver.get("https://registry.npmmirror.com/binary.html?path=chromedriver/")
    driver.find_element(By.XPATH, '/html/body/table/tbody/tr[156]/td[2]/a').click()
    time.sleep(3)
    driver.close()
    

    WebDriverWait 显式等待,很适合ui自动化

    import os
    import time
    
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.wait import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from utils.get_filepath import download_file_path
    
    path = download_file_path() + "/LATEST_RELEASE"
    if os.path.exists(path):
        print("文件存在")
        os.remove(path)
        print("文件已删除")
    
    chromeOptions = webdriver.ChromeOptions()
    prefs = {"download.default_directory": "{}".format(download_file_path())}
    chromeOptions.add_experimental_option("prefs", prefs)
    driver = webdriver.Chrome(chromeOptions)
    driver.maximize_window()
    driver.get("https://registry.npmmirror.com/binary.html?path=chromedriver/")
    locate = (By.XPATH,'/html/body/table/tbody/tr[156]/td[2]/a')
    element = WebDriverWait(driver,3).until(EC.visibility_of_element_located(locate),"找不到这个元素")
    # element = WebDriverWait(driver, 3).until(EC.url_contains("registry.npmmirror.com1"),"找不到这个元素")
    # element.click()
    time.sleep(3)
    driver.close()
    
    

    相关文章

      网友评论

          本文标题:38 selenium三种等待方式

          本文链接:https://www.haomeiwen.com/subject/fnipzdtx.html