selenmium常见配置
selenium
做web自动化时我们想要通过get打开一个页面之前就设置好一些基本参数,需要
通过add_argument()
方法来设置,下面以一个简单的不展示窗口为例。
option = webdriver.ChromeOptions() # 实例化ChromeOptions
option.add_argument('--headless') # 设置无窗口模式
driver = webdriver.Chrome(options=option) # 实例化Chrome
driver.implicitly_wait(10)
driver.get("https://www.baidu.com/")
除了headless外,还有如下几种参数最常用的
option.add_experimental_option("excludeSwitches", ["enable-automation"]) # 禁止浏览器被监控提示
option.add_argument("--user-agent=' '") # 设置请求头user-agent
option.add_argument('--start-maximized') # 设置窗口最大化
option.add_argument('--window-size=200,200') # 设置窗口大小
option.add_argument('--incognito') # 无痕模式
option.add_argument('--hide-scrollbars') # 隐藏滚动条
option.add_argument('--disable-javascript') # 禁用js
option.add_argument('--blink-settings=imagesEnabled=false') # 不加载图片(拦截图片)
option.add_argument('--disable-gpu') # 禁用gpu加速option.add_argument(r'--user-data-dir=C:\Users\v_lihongtao\AppData\Local\Google\Chrome\User Data1') # 打开窗口保存登录态
这里需要注意的是禁止浏览器被监控的提示用的是add_experimental_option()
方法。
打开窗口保持登录态需找到浏览器安装目录下复制user data路径,userdata就是你当前浏览器所处的状态,为了方便区分,我们可以先关闭浏览器所有的窗口,然后复制userdata文件更改成userdata1,然后添加后--user-data-dir
下。