今天跟大家分享的文章主要是介绍了Python爬虫使用代理IP的实现,文中通过示例代码介绍的非常详细,可能对很多的爬虫工作者来说简直是小儿科的东西,但是对一些刚入行的小白爬虫来说还是蛮有学习价值的,有这方面需求的小伙伴跟着我一起来学习吧。
当我们在使用爬虫进行数据获取时,如果目标网站对访问的速度或次数要求较高,那么你的 IP 就很容易被封掉,也就意味着在一段时间内无法再进行下一步的工作。这时候代理的重要性就显示出来了,因为不管网站怎么封,只要你的程序一直都有新的ip去访问就可以继续进行下一步的研究。
本文除了和大家交流下代理ip的重要性以外也会向大家分享下适合新手爬虫使用的代理模式,那就是动态隧道代理,网络上有很多代理商都有提供,但是各家质量有所区别,大家根据需要实际测试为准。这里分享下普便的隧道代理的使用方式:
// 要访问的目标页面 string targetUrl = "http://httpbin.org/ip"; // 代理服务器(产品官网 www.16yun.cn) string proxyHost = "http://t.16yun.cn"; string proxyPort = "31111"; // 代理验证信息 string proxyUser = "username"; string proxyPass = "password"; // 设置代理服务器 WebProxy proxy = new WebProxy(string.Format("{0}:{1}", proxyHost, proxyPort), true); ServicePointManager.Expect100Continue = false; var request = WebRequest.Create(targetUrl) as HttpWebRequest; request.AllowAutoRedirect = true; request.KeepAlive = true; request.Method = "GET"; request.Proxy = proxy; //request.Proxy.Credentials = CredentialCache.DefaultCredentials; request.Proxy.Credentials = new System.Net.NetworkCredential(proxyUser, proxyPass); // 设置Proxy Tunnel // Random ran=new Random(); // int tunnel =ran.Next(1,10000); // request.Headers.Add("Proxy-Tunnel", String.valueOf(tunnel)); //request.Timeout = 20000; //request.ServicePoint.ConnectionLimit = 512; //request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36"; //request.Headers.Add("Cache-Control", "max-age=0"); //request.Headers.Add("DNT", "1"); //String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(proxyUser + ":" + proxyPass)); //request.Headers.Add("Proxy-Authorization", "Basic " + encoded); using (var response = request.GetResponse() as HttpWebResponse) using (var sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { string htmlStr = sr.ReadToEnd(); }
以上就是关于爬虫中如何使用代理的示例,只是简单的分享了一部分,关于更多的我们下次再做更深的交流,以上就是本文的全部内容,希望对大家的学习有所帮助。