作为爬虫,我们都知道很多网站都有反爬措施,防止他人爬取数据,而封IP是最常见的反爬策略。通常他们的策略是发现你短时间内访问次数过多,就会封禁你的ip。这个策略的解决方法其实很简单。我们可以限制访问网站的频率或者添加IP代理池。.在爬虫程序中,我们只需要添加一个代理,例如!-*-encoding:utf-8-*-importrequestsimportrandom#要访问的目标页面targetUrl="http://www.weibo.com"#要访问的目标HTTPS页面#targetUrl="https://www.weibo.com"#代理服务器(产品官网www.16yun.cn)proxyHost="t.16yun.cn"proxyPort="31111"#代理隧道认证信息proxyUser="16VIZRXL"proxyPass="125478"proxyMeta="http://%(user)s:%(pass)s@%(host)s:%(port)s"%{"host":proxyHost,"port":proxyPort,"user":proxyUser,"pass":proxyPass,}#设置http和https访问都使用HTTP代理proxies={"http":proxyMeta,"https":proxyMeta,}#设置IP切换头tunnel=random.randint(1,10000)headers={"Proxy-Tunnel":str(tunnel)}resp=requests.get(targetUrl,proxies=proxies,headers=headers)printresp.status_codeprintresp.text本文只是粗略分享了反爬策略中的IP拦截行为网站,加个代理就可以轻松解决,主要是Python。希望能带你走上新的路,也希望能结识更多走在路上的前辈。
