QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

手机号码,快捷登录

泡泡马甲APP 更多内容请下载泡泡马甲手机客户端APP 立即下载 ×
查看: 4141|回复: 0

[C#] C#爬虫-Selenium ChromeDriver 设置代理

[复制链接]

等级头衔

积分成就    金币 : 2802
   泡泡 : 1516
   精华 : 6
   在线时间 : 1243 小时
   最后登录 : 2024-4-29

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老

联系方式
发表于 2021-10-8 07:55:13 | 显示全部楼层 |阅读模式
背景
/ w" {$ U, @, _# t6 u; [8 E       开发爬虫程序,如果不做代理设置,本机的外网IP很容易被网站封掉,导致不能持续进行数据抓取。而Selenium作为动态网页抓取的利器,我们有必要了解一下,如何对它进行代理设置,并正常访问网页。
- @$ m- ^  N9 P+ }3 c解决办法8 E( V3 e  \+ w, s0 T9 g+ Y7 L" {4 O
1、首先申请代理ip,正常付费的才比较靠谱。这其中包括账号、密码。
% }5 u" p- l8 k# H+ c6 L
  1.   private string proxy_Host = "域名地址";
  2.         private int proxy_Post = 端口;
  3.         private string proxy_UserName = "账号";
  4.         private string proxy_PassWord = "密码";
  5.         private string proxy_CheckURL = "检查是否正常的地址";
  6.         private string Ex_Proxy_Name = "proxy.zip";
2、设置chrome background.js、manifest.json
  1.   private bool Rebuild_Extension_Proxy(string proxy_UserName, string proxy_PassWord)
  2.         {
  3.             bool result = false;
  4.             FileStream zipToOpen = null;
  5.             ZipArchive archive = null;
  6.             ZipArchiveEntry readmeEntry = null;
  7.             StreamWriter writer = null;
  8.             string background = "";
  9.             string manifest = "";
  10.             try
  11.             {
  12.                 background = @"
  13.                 var Global = {
  14.                     currentProxyAouth:
  15.                     {
  16.                         username: '',
  17.                         password: ''
  18.                     }
  19.                 }
  20.                 Global.currentProxyAouth = {
  21.                         username: '" + proxy_UserName + @"',
  22.                         password: '" + proxy_PassWord + @"'
  23.                 }
  24.                 chrome.webRequest.onAuthRequired.addListener(
  25.                     function(details, callbackFn) {
  26.                         console.log('onAuthRequired >>>: ', details, callbackFn);
  27.                         callbackFn({
  28.                             authCredentials: Global.currentProxyAouth
  29.                         });
  30.                     }, {
  31.                         urls: [""<all_urls>""]
  32.                     }, [""asyncBlocking""]);
  33.                 chrome.runtime.onMessage.addListener(
  34.                     function(request, sender, sendResponse) {
  35.                         console.log('Background recieved a message: ', request);
  36.                         POPUP_PARAMS = {};
  37.                         if (request.command && requestHandler[request.command])
  38.                             requestHandler[request.command] (request);
  39.                     }
  40.                 );";
  41.                 manifest = @"
  42.                 {
  43.                     ""version"": ""1.0.0"",
  44.                     ""manifest_version"": 2,
  45.                     ""name"": ""Chrome Proxy"",
  46.                     ""permissions"": [
  47.                         ""proxy"",
  48.                         ""tabs"",
  49.                         ""unlimitedStorage"",
  50.                         ""storage"",
  51.                         ""<all_urls>"",
  52.                         ""webRequest"",
  53.                         ""webRequestBlocking""
  54.                     ],
  55.                     ""background"": {
  56.                         ""scripts"": [""background.js""]
  57.                     },
  58.                     ""minimum_chrome_version"":""22.0.0""
  59.                 }";
  60.                 zipToOpen = new FileStream(System.Environment.CurrentDirectory + "\" + Ex_Proxy_Name, FileMode.Create);
  61.                 archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update);
  62.                 readmeEntry = archive.CreateEntry("background.js");
  63.                 writer = new StreamWriter(readmeEntry.Open());
  64.                 writer.WriteLine(background);
  65.                 writer.Close();
  66.                 readmeEntry = archive.CreateEntry("manifest.json");
  67.                 writer = new StreamWriter(readmeEntry.Open());
  68.                 writer.WriteLine(manifest);
  69.                 writer.Close();
  70.                 result = true;
  71.             }
  72.             catch (Exception ex)
  73.             {
  74.                 result = false;
  75.             }
  76.             finally
  77.             {
  78.                 if (writer != null) { writer.Close(); writer.Dispose(); writer = null; }
  79.                 if (readmeEntry != null) { readmeEntry = null; }
  80.                 if (archive != null) { archive.Dispose(); archive = null; }
  81.                 if (zipToOpen != null) { zipToOpen.Close(); zipToOpen.Dispose(); zipToOpen = null; }
  82.             }
  83.             return result;
  84.         }
3、Chrome Driver使用代理Proxy* e) _! y& V' {  I( M2 k" O
  1. // 設置 Chrome Driver Exyension Proxy 設定
  2.                 bool isproxysetting = true;
  3.                 if (_isuseproxy)
  4.                 {
  5.                     isproxysetting = Rebuild_Extension_Proxy(proxy_UserName, proxy_PassWord);
  6.                 }
  7.                 if (isproxysetting)
  8.                 {
  9.                     // Driver 設定
  10.                     options = new ChromeOptions();
  11.                     if (_isuseproxy)
  12.                     {
  13.                         options.Proxy = null;
  14.                         options.AddArguments("--proxy-server=" + proxy_Host + ":" + proxy_Post.ToString());
  15.                         options.AddExtension(Ex_Proxy_Name);
  16.                     }
4、测试一下我们的设置3 N, K) e! G, c* o1 w
  1.   private Proxy_Unit.ProxyIPInfo Get_ProxyIPInfo(string Html_Content)
  2.         {
  3.             Proxy_Unit.ProxyIPInfo result = null;
  4.             try
  5.             {
  6.                 result = new Proxy_Unit.ProxyIPInfo();
  7.                 Html_Content = Html_Content.Replace("<html><head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">", "");
  8.                 Html_Content = Html_Content.Replace("</pre></body></html>", "");
  9.                 if (!Html_Content.Contains("proxy error"))
  10.                 {
  11.                     result = JsonConvert.DeserializeObject<Proxy_Unit.ProxyIPInfo>(Html_Content);
  12.                 }
  13.                 else
  14.                 {
  15.                     result = null;
  16.                 }
  17.             }
  18.             catch (Exception ex)
  19.             {
  20.                 result = null;
  21.             }
  22.             return result;
  23.         }
测试效果
  z1 ?: S5 T/ f" u$ Z成功,达到预期效果
- A% _- C/ |- Q* M. U" E3 D3 h; q3 L! ~/ p) U$ a
  1. {
  2.     "ip":"213.182.205.185",
  3.     "country":"IS",
  4.     "asn":{
  5.         "asnum":9009,
  6.         "org_name":"M247 Ltd"
  7.     },
  8.     "geo":{
  9.         "city":"Reykjavik",
  10.         "region":"1",
  11.         "region_name":"Capital Region",
  12.         "postal_code":"105",
  13.         "latitude":64.1369,
  14.         "longitude":-21.9139,
  15.         "tz":"Atlantic/Reykjavik",
  16.         "lum_city":"reykjavik",
  17.         "lum_region":"1"
  18.     }
  19. }
总结9 d) p, \1 y. i+ e1 u7 N
       我们之前测试要为ChromeDriver设定Proxy时有遇到许多困难,需要使用Chrome Extension的管道设定Proxy才成功,以上希望能让您比较好了解。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号 )

GMT+8, 2024-4-30 13:38

Powered by paopaomj X3.4 © 2016-2024 sitemap

快速回复 返回顶部 返回列表