Chrome 浏览器的 ChromeOptions

设置案例

class Options(object):
 
    def __init__(self):
        # 设置 chrome 二进制文件位置
        self._binary_location = ''
        # 添加启动参数
        self._arguments = []
        # 添加扩展应用
        self._extension_files = []
        self._extensions = []
        # 添加实验性质的设置参数
        self._experimental_options = {}
        # 设置调试器地址
        self._debugger_address = None


使用

try:
    # 创建谷歌浏览器驱动参数对象
    chrome_options = webdriver.ChromeOptions()
    # 不加载图片
    prefs = {"profile.managed_default_content_settings.images": 2}
    chrome_options.add_experimental_option("prefs", prefs)
    # 使用headless无界面浏览器模式
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--disable-gpu')
    # chrome_options.binary_location = r'...\chrome.exe'
 
    # 加载谷歌浏览器驱动
    driver = webdriver.Chrome(r'...\chromedriver.exe')
 
    # 请求地址
    driver.get('https://item.jd.com/100038004369.html')
    wait = WebDriverWait(driver,10)    # 等待10秒
    # 等待页面加载class名称为m-item-inner的节点,该节点中包含商品信息
    wait.until(EC.presence_of_element_located((By.CLASS_NAME,"w")))
 
    # 退出浏览器驱动
    driver.quit()
 
except Exception as e:
    print(e)

参数 含义
.add_argument('--disable-infobars') 禁止策略化
.add_argument('--no-sandbox') 解决DevToolsActivePort文件不存在的报错
.add_argument('window-size=1920x3000') 指定浏览器分辨率
.add_argument('--disable-gpu') 谷歌禁用GPU加速
.add_argument('--disable-javascript') 禁用javascript
.add_argument('--incognito') 隐身模式(无痕模式)
.add_argument('--start-maximized') 最大化运行(全屏窗口),不设置,取元素会报错
.add_argument('--hide-scrollbars') 隐藏滚动条, 应对一些特殊页面
.add_argument('blink-settings=imagesEnabled=false') 不加载图片, 提升速度
.add_argument('--headless') 浏览器不提供可视化页面(无头模式). linux下如果系统不支持可视化不加这条会启动失败
.add_argument('disable-infobars') 去掉Chrome提示受到自动软件控制
.add_argument('lang=en_US') 设置语言
.add_argument('User-Agent=xxxxxx') 设置User-Agent属性
.add_argument('--kiosk-printing') 默认打印机进行打印
.binary_location = r"...\chrome.exe" 手动指定使用的浏览器位置
.add_experimental_option("debuggerAddress", "127.0.0.1:9222") 调用原来的浏览器,不用再次登录即可重启
prefs = {"":""}
prefs["credentials_enable_service"] = False
prefs["profile.password_manager_enabled"] = False
.add_experimental_option("prefs", prefs) 设置prefs属性,屏蔽'保存密码'提示框
.add_experimental_option('excludeSwitches', ['enable-automation']) 以开发者模式启动调试chrome,可以去掉提示受到自动软件控制
.add_experimental_option('useAutomationExtension', False) 去掉提示以开发者模式调用

posted @ 2024-07-12 08:51  DreamDZhu  阅读(2)  评论(0编辑  收藏  举报