Selenium基本配置

本文介绍使用Selenium WebDriver进行自动化测试的方法,包括配置Chrome浏览器选项、模拟移动端设备、更改User-Agent、禁用图片加载等技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from selenium import webdriver
import time
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities


def getWeb(url):
    '''配置web浏览器'''
    options = webdriver.ChromeOptions()
    mobile_emulation = {"deviceName": "Galaxy S5"}
    capabilities = DesiredCapabilities.CHROME
    capabilities['loggingPrefs'] = {'browser': 'ALL'}
    # options = webdriver.ChromeOptions()
    options.add_experimental_option("mobileEmulation", mobile_emulation)
    # 修改windows.navigator.webdriver,防机器人识别机制,selenium自动登陆判别机制desired_capabilities=capabilities,
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    # 更换头部
    options.add_argument(
        'user-agent=mozilla/5.0 (iphone; cpu iphone os 5_1_1 like mac os x) applewebkit/534.46 (khtml, like gecko) mobile/9b206 micromessenger/5.0')
    # 禁用图片
    # 禁止图片和css加载
    # "profile.managed_default_content_settings.images": 2,
    prefs = {'permissions.default.stylesheet': 2}
    options.add_experimental_option("prefs", prefs)
    # #添加代理
    # ip,port = '127.0.0.1','8080'
    # options.add_argument(('--proxy-server=http://{}:{}'.format(ip,port)))#有的博客写的是'--proxy-server=http://',就目前我的电脑来看的话需要把http://去掉就可以用,他会自己加的
    # options.add_argument('-headless')  # 无头参数
    options.headless = True
    web = webdriver.Chrome(options=options)
    url = "https://work.zcst.edu.cn/default/work/jlzh/jkxxtb/jkxxcj.jsp"
    web.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """
        Object.defineProperty(navigator, 'webdriver', {
        get: () => undefined
        })
    """
    })
    web.set_page_load_timeout(30)
    web.set_script_timeout(30)  # 这两种设置都进行才有效
    web.get(url)
    return web
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值