帮助文档>代理IP>操作指南>调用方式 > Python自动化测试Selenium+chrome连接代理ip(账密模式)

Python自动化测试Selenium+chrome连接代理ip(账密模式)

发布时间:2023-03-28 16:01

此示例Python使用Selenium调用Chrome浏览器并通过代理进行自动化测试。

  • 代码示例
  1. import time
  2. import string
  3. import zipfile
  4. from selenium import webdriver
  5. from selenium.webdriver.chrome.service import Service
  6. targetURL = "http://myip.ipip.net" # 访问的目标站点
  7. proxyHost = "61.171.76.145" # 代理IP地址
  8. proxyPort = "50353" # 代理IP端口号
  9. authKey = "x" # 代理IP的AuthKey
  10. password = "x" # 代理IP的AuthPwd
  11. def create_proxy_auth_extension(proxy_host, proxy_port, proxy_username, proxy_password, scheme='http',
  12. plugin_path=None):
  13. if plugin_path is None:
  14. plugin_path = r'./{}_{}_qgnet_proxyauth_plugin.zip'.format(proxy_username, proxy_password)
  15. manifest_json = """
  16. {
  17. "version": "1.0.0",
  18. "manifest_version": 2,
  19. "name": "Chrome Proxy",
  20. "permissions": [
  21. "proxy",
  22. "tabs",
  23. "unlimitedStorage",
  24. "storage",
  25. "",
  26. "webRequest",
  27. "webRequestBlocking"
  28. ],
  29. "background": {
  30. "scripts": ["background.js"]
  31. },
  32. "minimum_chrome_version":"22.0.0"
  33. }
  34. """
  35. background_js = string.Template(
  36. """
  37. var config = {
  38. mode: "fixed_servers",
  39. rules: {
  40. singleProxy: {
  41. scheme: "${scheme}",
  42. host: "${host}",
  43. port: parseInt(${port})
  44. },
  45. bypassList: ["localhost"]
  46. }
  47. };
  48. chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
  49. function callbackFn(details) {
  50. return {
  51. authCredentials: {
  52. username: "${username}",
  53. password: "${password}"
  54. }
  55. };
  56. }
  57. chrome.webRequest.onAuthRequired.addListener(
  58. callbackFn,
  59. {urls: [""]},
  60. ['blocking']
  61. );
  62. """
  63. ).substitute(
  64. host=proxy_host,
  65. port=proxy_port,
  66. username=proxy_username,
  67. password=proxy_password,
  68. scheme=scheme,
  69. )
  70. with zipfile.ZipFile(plugin_path, 'w') as zp:
  71. zp.writestr("manifest.json", manifest_json)
  72. zp.writestr("background.js", background_js)
  73. return plugin_path
  74. if __name__ == '__main__':
  75. # 此处指定您的webdriver路径,版本需要跟您所使用的Chrome版本一致,
  76. # 下载地址https://registry.npmmirror.com/binary.html?path=chromedriver/
  77. driver_location = "./chromedriver/chromedriver_v106_win.exe"
  78. proxy_auth_plugin_path = create_proxy_auth_extension(
  79. proxy_host=proxyHost,
  80. proxy_port=proxyPort,
  81. proxy_username=authKey,
  82. proxy_password=password)
  83. option = webdriver.ChromeOptions()
  84. option.add_argument("--start-maximized") # 窗口最大化运行
  85. option.add_extension(proxy_auth_plugin_path) # 添加proxy插件
  86. # 此处selenium版本为4.8.0
  87. driver = webdriver.Chrome(service=Service(driver_location), options=option)
  88. driver.get(targetURL)
  89. time.sleep(100)
  90. driver.quit()
  • 运行结果
本文导读

客户热线:4007-567-365