0x00序言
批量获取代理IP详见上篇文章《分享项目_python爬取可用代理ip》,在大量爬取某个指定网站时,若该网站做了限制单位时间内同个ip的访问次数,则需要利用代理ip来帮助我们的爬虫项目完成请求。获取免费的代理IP很简单,百度免费代理IP即可,本文中在点击打开链接获取代理IP
0x01关键代码实现机理
首先获取足够的代理IP池,这在上篇文章中分享的项目可以快速搭建一个爬取代理IP池。
拿到足够的IP之后,我们即可用urllib库的request方法中的,ProxyHandler方法,build_opener方法,install_opener方法,这三个方法可以看做是使用代理IP的一个套路
截取官方文档的部分关键文档
classurllib.request.
ProxyHandler
(
proxies=None
)
Cause requests to go through a proxy. If proxies is given, it must be a dictionary mapping protocol names to URLs of proxies.
ProxyHandler官方文档翻译过来就是,通过代理方法请求,如果给定一个代理,它必须是一个字典映射,key为协议,value为URLs或者代理ip。urllib.request.
build_opener
(
[
handler,
...
]
)
Return an OpenerDirector
instance, which chains the handlers in the order given.
urllib.request.
install_opener
(
opener
)
Install an OpenerDirector
instance as the default global opener.
如果无法理解的话,可以把这三个方法当做一个套路来使用。
0x02整体代码思路
这次的思路很简单,就是以上方法的顺序使用。
1.将代理IP及其协议载入ProxyHandler赋给一个opener_support变量
2.将opener_support载入build_opener方法,创建opener
3.安装opener
0x03具体代码实现
from urllib import request
def ProxySpider(url, proxy_ip, header):
opener_support = request.ProxyHandler({'http': proxy_ip})
opener = request.build_opener(opener_support)
request.install_opener(opener)
req = request.Request(url, headers=header)
rsp = request.urlopen(req).read()
return rsp
你学会了吗?