此示例Python使用Selenium调用Chrome浏览器并通过代理进行自动化测试。
import timeimport stringimport zipfilefrom selenium import webdriverfrom selenium.webdriver.chrome.service import ServicetargetURL = "http://myip.ipip.net" # 访问的目标站点proxyHost = "61.171.76.145" # 代理IP地址proxyPort = "50353" # 代理IP端口号authKey = "x" # 代理IP的AuthKeypassword = "x" # 代理IP的AuthPwddef create_proxy_auth_extension(proxy_host, proxy_port, proxy_username, proxy_password, scheme='http', plugin_path=None): if plugin_path is None: plugin_path = r'./{}_{}_qgnet_proxyauth_plugin.zip'.format(proxy_username, proxy_password) manifest_json = """ { "version": "1.0.0", "manifest_version": 2, "name": "Chrome Proxy", "permissions": [ "proxy", "tabs", "unlimitedStorage", "storage", "", "webRequest", "webRequestBlocking" ], "background": { "scripts": ["background.js"] }, "minimum_chrome_version":"22.0.0" } """ background_js = string.Template( """ var config = { mode: "fixed_servers", rules: { singleProxy: { scheme: "${scheme}", host: "${host}", port: parseInt(${port}) }, bypassList: ["localhost"] } }; chrome.proxy.settings.set({value: config, scope: "regular"}, function() {}); function callbackFn(details) { return { authCredentials: { username: "${username}", password: "${password}" } }; } chrome.webRequest.onAuthRequired.addListener( callbackFn, {urls: [""]}, ['blocking'] ); """ ).substitute( host=proxy_host, port=proxy_port, username=proxy_username, password=proxy_password, scheme=scheme, ) with zipfile.ZipFile(plugin_path, 'w') as zp: zp.writestr("manifest.json", manifest_json) zp.writestr("background.js", background_js) return plugin_pathif __name__ == '__main__': # 此处指定您的webdriver路径,版本需要跟您所使用的Chrome版本一致, # 下载地址https://registry.npmmirror.com/binary.html?path=chromedriver/ driver_location = "./chromedriver/chromedriver_v106_win.exe" proxy_auth_plugin_path = create_proxy_auth_extension( proxy_host=proxyHost, proxy_port=proxyPort, proxy_username=authKey, proxy_password=password) option = webdriver.ChromeOptions() option.add_argument("--start-maximized") # 窗口最大化运行 option.add_extension(proxy_auth_plugin_path) # 添加proxy插件 # 此处selenium版本为4.8.0 driver = webdriver.Chrome(service=Service(driver_location), options=option) driver.get(targetURL) time.sleep(100) driver.quit()