selenium 使用的注意事项

Chrome 使用无头模式和声明屏幕大小

from selenium.webdriver import ChromeOptions

options = ChromeOptions()
# 如果想使用无界面模式, 将下行取消注释即可
# options.add_argument('--headless')
options.add_argument("--window-size=1200,800")
driver = webdriver.Chrome(options=options)

使用元素等待

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
try:
    WebDriverWait(driver, 10, 0.2).until(
        EC.presence_of_element_located((By.XPATH, '/html/frameset/frame[3]'))
    )
except Exception as reason:
    print('失败', reason)

切换frame

frame 和 iframe 使用下面的切换方式,其他 frame 按元素对待

# 切出到主文档
switch_to.default_content()
# 切换到frame
self.driver.switch_to.frame("menu")

保存屏幕截图

from PIL import Image
driver.save_screenshot(imgname)
原文地址:https://www.cnblogs.com/amnotgcs/p/13237740.html