python selenium(3)
Selenium在执行元素定位和操作时,可能会遇到页面尚未完全加载或元素尚不可见的情况,导致定位失败。
此时可以使用time库使进程短暂挂起:
import time
'''
网页跳转或刷新等情况前
'''
time.sleep(1)
'''
网页跳转后及元素定位
'''
但是可能出现时间设置过长或过短的问题
此时可以改进,使用:
while True:
try:
pass#想进行的操作
except:
time.sleep(1)
Selenium内置操作
Selenium在执行元素定位和操作时,可能会遇到页面尚未完全加载或元素尚不可见的情况,导致定位失败。
- 隐式等待(Implicit Waits)
隐式等待是一种全局的等待机制,它会在整个Selenium WebDriver实例的生命周期中生效,对所有定位操作有效。设置隐式等待后,Selenium将在查找元素时等待一定的时间,如果元素在指定的等待时间内出现,就会立即执行后续操作,否则将抛出NoSuchElementException异常。
from selenium import webdriver
# Create a WebDriver instance and set the implicit wait time to 10 seconds
driver = webdriver.Chrome()
driver.implicitly_wait(10)
# Open the target webpage
driver.get("https://www.example.com/")
# Perform actions on elements
element = driver.find_element_by_id("element_id")
element.click()
# Close the browser window
driver.quit()
- 显式等待(Explicit Waits)
显式等待是一种精确的等待机制,它会在指定的条件发生或超时后继续执行后续代码。可以使用WebDriverWait结合expected_conditions类来设置等待条件,直到满足条件或超过指定的最大等待时间。显式等待只对设置的特定元素生效。
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
# Create a WebDriver instance and open the target webpage
driver = webdriver.Chrome()
driver.get("https://www.example.com/")
# Explicitly wait until the element with ID 'element_id' is visible (maximum wait time: 10 seconds)
element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.ID, "element_id"))
)
# Perform actions on the element
element.click()
# Close the browser window
driver.quit()