当写好selenium代码后运行发行无法定位元素,则这个时候就要考虑
- 程序运行太快导致 网页元素标签之类的还未加载成功
- 网速差劲
所以说要设置等待时间,等待元素加载出来
- 强制等待 即 sleep time.sleep(3) 显性的设置等待时间 有点傻
- 显性等待
WebDriverWait(driver,20,0.5).until(expected_conditions.prosence_of_element_located(locator))
selenium 中的wait模块的WebDriverWait() 方法,配合until或者until_not 方法,再辅助以一些判断条件,
每经过多少秒就查看locator元素是否可见,如果可见就停止等待,如果不可见就继续等待,直到报超时异常
实际例子
#! /opt/anaconda3/bin/python3
#脚本第一句声明采用什么解释器,然后直接将脚本放到PATH里面即可
import sys
#建议采用chrome比firefox启动快一点,也更好看点
#目前采用chromium-driver自动升级省去了配置升级的麻烦
#要不然还得下载相应版本的驱动,更新后又是麻烦
from selenium import webdriver
chrome_options = webdriver.ChromeOptions();
#隐私模式
chrome_options.add_argument("--incognito")
#新的设置忽略头部的chrome is auto controlled 信息
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation']);
driver = webdriver.Chrome