Selenium中的option用法实例
在上一篇文章Selenium中免登录的实现方法一option中我们用到了option,而option的用法是很多的,本文举几个例子
关于无头浏览器,也属于option的一种,但我们单独开个篇幅讲一下
1. 无痕模式
from selenium import webdriver
myoption = webdriver.ChromeOptions()
myoption.add_argument('--incognito')
driver = webdriver.Chrome(options=myoption)
2. 启动时窗口大小设置
- 最大化
from selenium import webdriver
myoption = webdriver.ChromeOptions()
myoption.add_argument('--start-maximized')
driver = webdriver.Chrome(options=myoption)
- 指定大小
from selenium import webdriver
myoption = webdriver.ChromeOptions()
myoption.add_argument('--window-size=800,600')
driver = webdriver.Chrome(options=myoption)
- 指定比例:这里有点坑,你得到的size是整数,但/了之后就是浮点数,此处参数只支持整数。
from selenium import webdriver
import pyautogui
myoption = webdriver.ChromeOptions()
width,height = pyautogui.size()
myoption.add_argument(f'--window-size={round(width/3)},{round(height/3)}')
driver = webdriver.Chrome(options=myoption)
3. 去掉浏览器被自动化软件控制的提示
from selenium import webdriver
myoption = webdriver.ChromeOptions()
myoption.add_experimental_option("excludeSwitches", ["enable-automation"])
myoption.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=myoption)
4. 伪造user-agent
from selenium import webdriver
# from fake_useragent import UserAgent # 以前是这个库,现在链接外部网站有点问题,就改用本地库了
from local_fake_useragent import UserAgent # pip install local-fake-useragent
chrome_ua = UserAgent('chrome').rget
print(chrome_ua) # Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/534.16 SUSE/10.0.626.0 (KHTML, like Gecko) Chrome/10.0.626.0 Safari/534.16
options = webdriver.ChromeOptions()
options.add_argument(f'user-agent={chrome_ua}')
driver = webdriver.Chrome(options=options)
driver.get('https://cn.bing.com')
5. 禁止弹窗
iqiyi的首页打开的时候会弹出 允许禁止,这个可以ban掉
from selenium import webdriver
prefs = {
'profile.default_content_setting_values': {
'notifications': 2
}
}
myoption = webdriver.ChromeOptions()
myoption.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(options=myoption)
driver.get('https://www.iqiyi.com/')
标签:webdriver,option,driver,Selenium,options,实例,import,myoption
From: https://www.cnblogs.com/wuxianfeng023/p/16978076.html