已经找到“” 的记录65条
Python自动化测试Selenium+chrome连接代理ip(账密模式)

此示例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. "<all_urls>",
  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: ["<all_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()
  • 运行结果
Python自动化测试Selenium+chrome连接代理ip(白名单模式)

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

  • 代码示例
  1. from selenium import webdriver
  2. from selenium.webdriver.chrome.service import Service
  3. targetURL = "http://myip.ipip.net" #访问的目标站点
  4. proxyAddr = "您的代理IP:端口号"
  5. if __name__ == '__main__':
  6. browser_location = r".\Chrome\chrome.exe" #指定浏览器路径位置
  7. driver_location = r".\Chrome\chromedriver.exe" #指定Driver路径位置
  8. option = webdriver.ChromeOptions()
  9. option.binary_location = browser_location #设置浏览器位置
  10. option.add_argument("--start-maximized") #窗口最大化运行
  11. option.add_argument('--proxy-server=%(server)s' % {"server": proxyAddr})
  12. driver = webdriver.Chrome(service=Service(driver_location), options=option)
  13. driver.get(targetURL)
  14. print(driver.page_source)
  • 运行结果

img

隧道代理(固定时长)python语言代码示例
  1. import base64
  2. import time
  3. import requests
  4. from requests.adapters import HTTPAdapter
  5. auth_key = "请改成您的Key"
  6. password = "请改成您的AuthPwd"
  7. tunnel_server = "http://请改成您的隧道地址" # 如:tunnel3.qg.net:19263
  8. target_url = "https://ip.cn/api/index?ip=&type=0" # 要访问的目标地址
  9. proxy_headers = {}
  10. proxy = {
  11. "http": tunnel_server,
  12. "https": tunnel_server
  13. }
  14. def encode_authorization(key, passwd):
  15. # python 使用 bytes 类型进行 base64 编码
  16. basic_str = bytes("%s:%s" % (key, passwd), "ascii")
  17. # 得到的返回值也是 bytes 类型,所以需要再 decode 为字符串
  18. return "Basic %s" % base64.b64encode(basic_str).decode("utf-8")
  19. def reset_tunnel_proxy_headers():
  20. global proxy_headers
  21. proxy_headers = {
  22. tunnel_server: {
  23. "Proxy-Authorization": encode_authorization(auth_key, password)
  24. }
  25. }
  26. def update_tunnel_proxy_headers(key, val):
  27. global proxy_headers
  28. proxy_headers[tunnel_server][key] = val
  29. def new_session():
  30. adapter = TunnelProxyAdapter()
  31. se = requests.Session()
  32. se.mount('https://', adapter)
  33. se.mount('http://', adapter)
  34. return se
  35. class TunnelProxyAdapter(requests.adapters.HTTPAdapter):
  36. def proxy_headers(self, p):
  37. if p in proxy_headers:
  38. print("session with headers:", proxy_headers[p])
  39. return proxy_headers[p]
  40. else:
  41. return None
  42. def multi_channel_tunnel():
  43. """
  44. 结果类似:
  45. request on multi channel
  46. request id: 1 , channel id: channel-1, code: 200, result: 183.155.88.224
  47. request id: 2 , channel id: channel-2, code: 200, result: 125.112.38.153
  48. request id: 3 , channel id: channel-3, code: 200, result: 183.155.89.125
  49. request id: 4 , channel id: channel-4, code: 200, result: 49.71.121.169
  50. request id: 5 , channel id: channel-5, code: 200, result: 115.210.67.220
  51. request id: 6 , channel id: channel-6, code: 200, result: 36.25.41.178
  52. request id: 7 , channel id: channel-7, code: 200, result: 180.125.162.116
  53. request id: 8 , channel id: channel-8, code: 200, result: 140.250.150.158
  54. request id: 9 , channel id: channel-9, code: 200, result: 121.227.102.227
  55. request id: 10, channel id: channel-10, code: 200, result: 49.88.106.198
  56. request id: 1 , channel id: channel-1, code: 200, result: 183.155.88.224
  57. request id: 2 , channel id: channel-2, code: 200, result: 125.112.38.153
  58. request id: 3 , channel id: channel-3, code: 200, result: 183.155.89.125
  59. request id: 4 , channel id: channel-4, code: 200, result: 49.71.121.169
  60. request id: 5 , channel id: channel-5, code: 200, result: 115.210.67.220
  61. request id: 6 , channel id: channel-6, code: 200, result: 36.25.41.178
  62. request id: 7 , channel id: channel-7, code: 200, result: 180.125.162.116
  63. request id: 8 , channel id: channel-8, code: 200, result: 140.250.150.158
  64. request id: 9 , channel id: channel-9, code: 200, result: 121.227.102.227
  65. request id: 10, channel id: channel-10, code: 200, result: 49.88.106.198
  66. """
  67. print("request on multi channel")
  68. reset_tunnel_proxy_headers()
  69. for i in range(1, 11):
  70. se = new_session()
  71. chan_id = "channel-%s" % i
  72. update_tunnel_proxy_headers("Proxy-TunnelID", chan_id)
  73. resp = se.get(target_url, proxies=proxy, headers={"Connection": "close"})
  74. print("request id: %-2s, channel id: %s, code: %s, result: %s" % (i, chan_id, resp.status_code, resp.text))
  75. time.sleep(10)
  76. # 因为固定时长为1分钟,所以在1分钟内继续使用已有通道,仍是之前的IP
  77. for i in range(1, 11):
  78. se = new_session()
  79. chan_id = "channel-%s" % i
  80. update_tunnel_proxy_headers("Proxy-TunnelID", chan_id)
  81. resp = se.get(target_url, proxies=proxy, headers={"Connection": "close"})
  82. print("request id: %-2s, channel id: %s, code: %s, result: %s" % (i, chan_id, resp.status_code, resp.text))
  83. if __name__ == "__main__":
  84. multi_channel_tunnel()
隧道代理(固定时长)Go语言代码示例
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "net/url"
  7. "sync"
  8. "time"
  9. )
  10. /** 返回内容
  11. 第一次循环
  12. 当前 IP:121.230.91.188 来自于:中国 江苏 泰州 电信
  13. 当前 IP:60.184.205.115 来自于:中国 浙江 丽水 电信
  14. 当前 IP:125.112.205.149 来自于:中国 浙江 金华 电信
  15. 当前 IP:60.184.108.175 来自于:中国 浙江 丽水 电信
  16. 当前 IP:58.214.87.31 来自于:中国 江苏 无锡 电信
  17. 当前 IP:183.143.131.24 来自于:中国 浙江 湖州 电信
  18. 当前 IP:42.53.99.119 来自于:中国 辽宁 锦州 联通
  19. 当前 IP:59.60.142.70 来自于:中国 福建 漳州 电信
  20. 当前 IP:114.226.175.159 来自于:中国 江苏 常州 电信
  21. 当前 IP:123.162.194.223 来自于:中国 河南 驻马店 电信
  22. max channel reached
  23. 第二次循环
  24. 当前 IP:114.226.175.159 来自于:中国 江苏 常州 电信
  25. 当前 IP:60.184.205.115 来自于:中国 浙江 丽水 电信
  26. 当前 IP:121.230.91.188 来自于:中国 江苏 泰州 电信
  27. 当前 IP:125.112.205.149 来自于:中国 浙江 金华 电信
  28. 当前 IP:123.162.194.223 来自于:中国 河南 驻马店 电信
  29. 当前 IP:58.214.87.31 来自于:中国 江苏 无锡 电信
  30. 当前 IP:183.143.131.24 来自于:中国 浙江 湖州 电信
  31. 当前 IP:60.184.108.175 来自于:中国 浙江 丽水 电信
  32. 当前 IP:59.60.142.70 来自于:中国 福建 漳州 电信
  33. 当前 IP:42.53.99.119 来自于:中国 辽宁 锦州 联通
  34. 第二次循环返回的IP与第一次循环相同,因为goroutine是异步的,所以返回顺序和第一次不一致
  35. myip.ipip.net服务器可能比较容易失败,用户可以自己找一个其他获取客户端IP的服务器来测试
  36. */
  37. // 固定时长多通道隧道模式
  38. func main() {
  39. authKey := "请改成您的Key" //固定时长1分钟的隧道,通道数10
  40. password := "请改成您的AuthPwd"
  41. proxyServer := "请改成您的隧道地址" //如:tunnel3.qg.net:19263
  42. targetURL := "https://ip.cn/api/index?ip=&type=0"
  43. rawURL := fmt.Sprintf("http://%s:%s@%s", authKey, password, proxyServer)
  44. proxyUrl, _ := url.Parse(rawURL)
  45. wg := sync.WaitGroup{}
  46. wg.Add(11)
  47. // 十个通道分别使用不同的十个IP,第十一次会返回错误,通道数超出
  48. for i := 0; i < 11; i++ {
  49. go func(index int) {
  50. defer wg.Done()
  51. client := http.Client{
  52. Transport: &http.Transport{
  53. ProxyConnectHeader: http.Header{
  54. "Proxy-TunnelID": []string{fmt.Sprintf("channel-%d", index)}, // 指定通道ID
  55. },
  56. Proxy: http.ProxyURL(proxyUrl),
  57. },
  58. }
  59. req, _ := http.NewRequest("GET", targetURL, nil)
  60. rsp, err := client.Do(req)
  61. if err != nil {
  62. fmt.Printf("request failed: %s\n", err)
  63. return
  64. }
  65. defer rsp.Body.Close()
  66. body, err := ioutil.ReadAll(rsp.Body)
  67. if err != nil {
  68. fmt.Println(err)
  69. } else {
  70. fmt.Println(string(body))
  71. }
  72. }(i)
  73. }
  74. wg.Wait()
  75. // 因为固定时长为1分钟,所以在1分钟内继续使用已有通道,仍是之前的IP
  76. time.Sleep(time.Second * 10)
  77. wg.Add(10)
  78. for i := 0; i < 10; i++ {
  79. go func(index int) {
  80. defer wg.Done()
  81. client := http.Client{
  82. Transport: &http.Transport{
  83. ProxyConnectHeader: http.Header{
  84. "Proxy-TunnelID": []string{fmt.Sprintf("channel-%d", index)}, // 指定通道ID
  85. },
  86. Proxy: http.ProxyURL(proxyUrl),
  87. },
  88. }
  89. req, _ := http.NewRequest("GET", targetURL, nil)
  90. rsp, err := client.Do(req)
  91. if err != nil {
  92. fmt.Printf("request failed: %s\n", err)
  93. return
  94. }
  95. defer rsp.Body.Close()
  96. body, err := ioutil.ReadAll(rsp.Body)
  97. if err != nil {
  98. fmt.Println(err)
  99. } else {
  100. fmt.Println(string(body))
  101. }
  102. }(i)
  103. }
  104. wg.Wait()
  105. }
隧道代理(动态请求)python语言代码示例

普通模式

  1. import requests
  2. targetURL = "https://ip.cn/api/index?ip=&type=0" //要访问的目标地址
  3. proxyAddr = "请改成您的隧道地址" //如:tunnel3.qg.net:19263
  4. authKey = "请改成您的Key"
  5. password = "请改成您的AuthPwd"
  6. # 账密模式
  7. proxyUrl = "http://%(user)s:%(password)s@%(server)s" % {
  8. "user": authKey,
  9. "password": password,
  10. "server": proxyAddr,
  11. }
  12. proxies = {
  13. "http": proxyUrl,
  14. "https": proxyUrl,
  15. }
  16. for i in range(10):
  17. resp = requests.get(targetURL, proxies=proxies)
  18. print(resp.text)

打标记模式

  1. import base64
  2. import time
  3. import requests
  4. from requests.adapters import HTTPAdapter
  5. auth_key = "请改成您的Key"
  6. password = "请改成您的AuthPwd"
  7. tunnel_server = "http://请改成您的隧道地址" //如:tunnel3.qg.net:19263
  8. target_url = "https://ip.cn/api/index?ip=&type=0" // 要访问的目标地址
  9. proxy_headers = {}
  10. proxy = {
  11. "http": tunnel_server,
  12. "https": tunnel_server
  13. }
  14. def encode_authorization(key, passwd):
  15. # python 使用 bytes 类型进行 base64 编码
  16. basic_str = bytes("%s:%s" % (key, passwd), "ascii")
  17. # 得到的返回值也是 bytes 类型,所以需要再 decode 为字符串
  18. return "Basic %s" % base64.b64encode(basic_str).decode("utf-8")
  19. def reset_tunnel_proxy_headers():
  20. global proxy_headers
  21. proxy_headers = {
  22. tunnel_server: {
  23. "Proxy-Authorization": encode_authorization(auth_key, password)
  24. }
  25. }
  26. def update_tunnel_proxy_headers(key, val):
  27. global proxy_headers
  28. proxy_headers[tunnel_server][key] = val
  29. def new_session():
  30. adapter = TunnelProxyAdapter()
  31. se = requests.Session()
  32. se.mount('https://', adapter)
  33. se.mount('http://', adapter)
  34. return se
  35. class TunnelProxyAdapter(requests.adapters.HTTPAdapter):
  36. def proxy_headers(self, p):
  37. if p in proxy_headers:
  38. print("session with headers:", proxy_headers[p])
  39. return proxy_headers[p]
  40. else:
  41. return None
  42. def normal_tunnel():
  43. """
  44. 结果类似:
  45. request on normal mode
  46. session with headers: {'Proxy-Authorization': 'Basic xxxx'}
  47. request id: 1, code: 200, result: 140.250.149.229
  48. """
  49. reset_tunnel_proxy_headers()
  50. print("request on normal mode")
  51. resp = new_session().get(target_url, proxies=proxy)
  52. print("request id: 1, code: %s, result: %s" % (resp.status_code, resp.text))
  53. def mark_tunnel():
  54. """
  55. 结果类似:
  56. request with mark
  57. session with headers: {'Proxy-Authorization': 'Basic xxxx', 'Proxy-TunnelID': 'channel-1', 'Proxy-TTL': 10}
  58. request id: 1 , code: 200, result: 183.166.118.48
  59. request id: 2 , code: 200, result: 183.166.118.48
  60. request id: 3 , code: 200, result: 183.166.118.48
  61. request id: 4 , code: 200, result: 183.166.118.48
  62. request id: 5 , code: 200, result: 183.166.118.48
  63. request id: 6 , code: 200, result: 183.166.118.48
  64. request id: 7 , code: 200, result: 183.142.59.203
  65. request id: 8 , code: 200, result: 183.142.59.203
  66. request id: 9 , code: 200, result: 183.142.59.203
  67. request id: 10, code: 200, result: 123.54.235.89
  68. """
  69. reset_tunnel_proxy_headers()
  70. update_tunnel_proxy_headers("Proxy-TunnelID", "channel-1")
  71. update_tunnel_proxy_headers("Proxy-TTL", 10)
  72. se = new_session()
  73. print("request with mark")
  74. for i in range(1, 12):
  75. resp = se.get(target_url, proxies=proxy, headers={"Connection": "close"})
  76. print("request id: %-2s, code: %s, result: %s" % (i, resp.status_code, resp.text))
  77. time.sleep(1)
  78. if __name__ == "__main__":
  79. normal_tunnel()
  80. mark_tunnel()
隧道代理(动态请求)Go语言代码示例

普通模式

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "net/url"
  7. "sync"
  8. "time"
  9. )
  10. func main() {
  11. authKey := "请改成您的Key"
  12. password := "请改成您的AuthPwd"
  13. proxyServer := "请改成您的隧道地址" //如:tunnel3.qg.net:19263
  14. targetURL := "https://ip.cn/api/index?ip=&type=0"
  15. rawURL := fmt.Sprintf("http://%s:%s@%s", authKey, password, proxyServer)
  16. proxyUrl, _ := url.Parse(rawURL)
  17. client := http.Client{
  18. Transport: &http.Transport{
  19. Proxy: http.ProxyURL(proxyUrl),
  20. },
  21. }
  22. req, _ := http.NewRequest("GET", targetURL, nil)
  23. rsp, err := client.Do(req)
  24. if err != nil {
  25. fmt.Printf("request failed: %s\n", err)
  26. return
  27. }
  28. defer rsp.Body.Close()
  29. body, err := ioutil.ReadAll(rsp.Body)
  30. if err != nil {
  31. fmt.Println(err)
  32. } else {
  33. fmt.Println(string(body))
  34. }
  35. }

打标记模式

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "net/url"
  7. "sync"
  8. "time"
  9. )
  10. /** 返回内容
  11. 当前 IP:114.219.115.191 来自于:中国 江苏 苏州 电信
  12. 当前 IP:114.219.115.191 来自于:中国 江苏 苏州 电信
  13. 当前 IP:114.219.115.191 来自于:中国 江苏 苏州 电信
  14. 当前 IP:114.219.115.191 来自于:中国 江苏 苏州 电信
  15. 当前 IP:114.219.115.191 来自于:中国 江苏 苏州 电信
  16. 当前 IP:114.219.115.191 来自于:中国 江苏 苏州 电信
  17. 当前 IP:114.219.115.191 来自于:中国 江苏 苏州 电信
  18. 当前 IP:114.219.115.191 来自于:中国 江苏 苏州 电信
  19. 当前 IP:114.219.115.191 来自于:中国 江苏 苏州 电信
  20. 当前 IP:114.219.115.191 来自于:中国 江苏 苏州 电信
  21. 当前 IP:14.118.211.116 来自于:中国 广东 江门 电信
  22. */
  23. func main() {
  24. authKey := "请改成您的Key"
  25. password := "请改成您的AuthPwd"
  26. proxyServer := "请改成您的隧道的地址" //如:tunnel3.qg.net:19263
  27. targetURL := "https://ip.cn/api/index?ip=&type=0"
  28. rawURL := fmt.Sprintf("http://%s:%s@%s", authKey, password, proxyServer)
  29. proxyUrl, _ := url.Parse(rawURL)
  30. client := http.Client{
  31. Transport: &http.Transport{
  32. ProxyConnectHeader: http.Header{
  33. "Proxy-TunnelID": []string{"channel-1"}, // 在CONNECT连接中新增Proxy-TunnelID打标记
  34. "Proxy-TTL": []string{"10"}, // Proxy-TTL指定该标记IP的存活时间
  35. },
  36. Proxy: http.ProxyURL(proxyUrl),
  37. },
  38. }
  39. // 因为标记的存活时间是10s,所以循环11次中有10次的IP是一样的。
  40. // 第11次因为标记的IP到期了,系统会自动替换IP
  41. wg := sync.WaitGroup{}
  42. wg.Add(11)
  43. for i := 0; i < 11; i++ {
  44. go func() {
  45. defer wg.Done()
  46. req, _ := http.NewRequest("GET", targetURL, nil)
  47. rsp, err := client.Do(req)
  48. if err != nil {
  49. fmt.Printf("request failed: %s\n", err)
  50. return
  51. }
  52. defer rsp.Body.Close()
  53. body, err := ioutil.ReadAll(rsp.Body)
  54. if err != nil {
  55. fmt.Println(err)
  56. } else {
  57. fmt.Println(string(body))
  58. }
  59. }()
  60. time.Sleep(time.Second)
  61. }
  62. wg.Wait()
  63. }
Node语言代码示例

nodejs http

  1. const http = require("http");
  2. const url = require("url");
  3. const targetURL = url.parse("https://ip.cn/api/index?ip=&type=0");
  4. const proxyIp = "您的代理IP";
  5. const proxyPort = 端口号;
  6. const authKey = "请改成您的Key";
  7. const password = "请改成您的AuthPwd";
  8. const base64 = new Buffer.from(authKey + ":" + password).toString("base64");
  9. const options = {
  10. host: proxyIp,
  11. port: proxyPort,
  12. path: targetURL,
  13. method: "GET",
  14. headers: {
  15. "Host": urlParsed.hostname,
  16. "Proxy-Authorization": "Basic " + base64
  17. }
  18. };
  19. http.request(options, function (resp) {
  20. console.log("response status code: " + resp.statusCode);
  21. resp.pipe(process.stdout);
  22. }).on("error", function (err) {
  23. console.log("request failed: " + err);
  24. }).end();

nodejs request

  1. const request = require("request");
  2. const targetUrl = "https://ip.cn/api/index?ip=&type=0";
  3. const proxyIp = "您的代理IP";
  4. const proxyPort = 端口号;
  5. const authKey = "请改成您的Key";
  6. const password = "请改成您的AuthPwd";
  7. const proxyUrl = "http://" + authKey + ":" + password + "@" + proxyIp + ":" + proxyPort;
  8. const req = request.defaults({'proxy': proxyUrl});
  9. const options = {
  10. url: targetUrl,
  11. headers: {}
  12. };
  13. req.get(options, function (err, resp, body) {
  14. if (err) {
  15. return console.log(err);
  16. }
  17. console.log("response status code: " + resp.statusCode);
  18. console.log("response body: " + body);
  19. }).on("error", function (err) {
  20. console.log("request failed: " + err);
  21. });

nodejs superagent

  1. const request = require("superagent");
  2. require("superagent-proxy")(request);
  3. const targetUrl = "https://ip.cn/api/index?ip=&type=0";
  4. const proxyIp = "您的代理IP";
  5. const proxyPort = 端口号;
  6. const authKey = "请改成您的Key";
  7. const password = "请改成您的AuthPwd";
  8. const proxyUrl = "http://" + authKey + ":" + password + "@" + proxyIp + ":" + proxyPort;
  9. request.get(targetUrl).proxy(proxyUrl).end(function onResponse(err, resp) {
  10. if (err) {
  11. return console.log(err);
  12. }
  13. console.log("response status code: " + resp.statusCode);
  14. console.log("response body: " + resp.text);
  15. });

nodejs axios

  1. const axios = require("axios")
  2. const {HttpsProxyAgent} = require("https-proxy-agent")
  3. const targetUrl = "http://ip.cn/api/index?ip=&type=0"
  4. const proxyIp = "您的代理IP"
  5. const proxyPort = 端口号
  6. const authKey = "请改成您的Key"
  7. const password = "请改成您的AuthPwd"
  8. const proxy = new HttpsProxyAgent(`http://${authKey}:${password}@${proxyIp}:${proxyPort}`)
  9. axios.get(targetUrl, {
  10. httpAgent: proxy,
  11. httpsAgent: proxy,
  12. }).then(function (response) {
  13. console.log("response body: " + response.data)
  14. }).catch(function (error) {
  15. console.log("request failed: " + error)
  16. }).finally(function () {
  17. console.log("request finished.")
  18. })
  19. // 如果目标站是HTTPS,则需要使用下面的代码进行代理请求
  20. let httpsProxyAgent = require('https-proxy-agent');
  21. var agent = new httpsProxyAgent(`http://${authKey}:${password}@${proxyIp}:${proxyPort}`);
  22. var config = {
  23. url: "https://ip.cn/api/index?ip=&type=0",
  24. httpsAgent: agent
  25. }
  26. axios.request(config)
  27. .then(function(response) {
  28. console.log("response body: " + response.data)
  29. }).catch(function(error) {
  30. console.log("request failed: " + error)
  31. })
C#语言代码示例
  1. string targetUrl = "https://ip.cn/api/index?ip=&type=0";
  2. string proxyIp = "您的代理IP";
  3. string proxyPort = "端口号";
  4. string authKey = "请改成您的Key";
  5. string password = "请改成您的AuthPwd";
  6. WebProxy proxy = new WebProxy(string.Format("{0}:{1}", proxyIp, proxyPort), true);
  7. proxy.Credentials = new NetworkCredential(authKey, password);
  8. ServicePointManager.Expect100Continue = false;
  9. var request = WebRequest.Create(targetUrl) as HttpWebRequest;
  10. request.AllowAutoRedirect = true;
  11. request.KeepAlive = true;
  12. request.Method = "GET";
  13. request.Proxy = proxy;
  14. request.Timeout = 10000;
  15. request.ServicePoint.ConnectionLimit = 16;
  16. using (var resp = request.GetResponse() as HttpWebResponse)
  17. using (var reader = new StreamReader(resp.GetResponseStream(), Encoding.UTF8)){
  18. string htmlStr = reader.ReadToEnd();
  19. }
Shell语言代码示例
  1. #!/bin/bash
  2. targetURL="https://ip.cn/api/index?ip=&type=0"
  3. proxyAddr="您的代理IP:端口号"
  4. authKey="请改成您的Key"
  5. password="请改成您的AuthPwd"
  6. curl -x ${authKey}:${password}@${proxyAddr} ${targetURL} -vvvv
Go语言代码示例
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "net/url"
  7. )
  8. func main() {
  9. authKey := "请改成您的Key"
  10. password := "请改成您的AuthPwd"
  11. proxyServer := "您的代理IP:端口号"
  12. targetURL := "https://ip.cn/api/index?ip=&type=0"
  13. rawURL := fmt.Sprintf("http://%s:%s@%s", authKey, password, proxyServer)
  14. proxyUrl, err := url.Parse(rawURL)
  15. if err != nil {
  16. panic(err)
  17. }
  18. client := http.Client{
  19. Transport: &http.Transport{
  20. Proxy: http.ProxyURL(proxyUrl),
  21. },
  22. }
  23. req, _ := http.NewRequest("GET", targetURL, nil)
  24. rsp, err := client.Do(req)
  25. if err != nil {
  26. fmt.Printf("request failed: %s\n", err)
  27. return
  28. }
  29. defer rsp.Body.Close()
  30. body, err := ioutil.ReadAll(rsp.Body)
  31. if err != nil {
  32. fmt.Println(err)
  33. } else {
  34. fmt.Println(string(body))
  35. }
  36. }

客户热线: