Python爬虫使用代理IP的实现
使用爬虫时,如果目标网站对访问的速度或次数要求较高,那么你的
目前很多网站都提供了一些免费的代理
测试的网址是:http://www.jshk.com.cn/,访问该站点可以得到请求的一些相关信息,其中 origin 字段就是客户端的 IP,根据它来判断代理是否设置成功,也就是是否成功伪装了IP
获取
代理池使用ip.hahado.cn:5555/random
只要访问这个接口再返回内容就可以拿到
Urllib
先看一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | fromurllib.error importURLError importurllib.request fromurllib.request importProxyHandler, build_opener # 获取IP ip_response =urllib.request.urlopen("http://localhost:5555/random") ip =ip_response.read().decode('utf-8') proxy_handler =ProxyHandler({ 'http': 'http://'+ip, 'https': 'https://'+ip }) opener =build_opener(proxy_handler) try: response =opener.open('http://httpbin.org/get') print(response.read().decode('utf-8')) exceptURLError as e: print(e.reason) |
运行结果:
1 2 3 4 5 6 7 8 9 10 | { "args": {}, "headers": { "Accept-Encoding": "identity", "Host": "httpbin.org", "User-Agent": "Python-urllib/3.7" }, "origin": "108.61.201.231, 108.61.201.231", "url": "https://httpbin.org/get" } |
Urllib 使用 ProxyHandler 设置代理,参数是字典类型,键名为协议类型,键值是代理,代理前面需要加上协议,即 http 或 https,当请求的链接是 http 协议的时候,它会调用 http 代理,当请求的链接是 https 协议的时候,它会调用https代理,所以此处生效的代理是:http://108.61.201.231 和 https://108.61.201.231
ProxyHandler 对象创建之后,再利用 build_opener() 方法传入该对象来创建一个 Opener,这样就相当于此 Opener 已经设置好代理了,直接调用它的 open() 方法即可使用此代理访问链接
Requests
Requests 的代理设置只需要传入 proxies 参数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | importrequests # 获取IP ip_response =requests.get("http://localhost:5555/random") ip =ip_response.text proxies ={ 'http': 'http://'+ip, 'https': 'https://'+ip, } try: response =requests.get('http://httpbin.org/get', proxies=proxies) print(response.text) exceptrequests.exceptions.ConnectionError as e: print('Error', e.args) |
运行结果:
1 2 3 4 5 6 7 8 9 10 11 | { "args": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Host": "httpbin.org", "User-Agent": "python-requests/2.21.0" }, "origin": "47.90.28.54, 47.90.28.54", "url": "https://httpbin.org/get" } |
Requests 只需要构造代理字典然后通过 proxies 参数即可设置代理,比较简单
Selenium
1 2 3 4 5 6 7 8 9 10 11 12 13 | importrequests fromselenium importwebdriver importtime # 借助requests库获取IP ip_response =requests.get("http://localhost:5555/random") ip =ip_response.text chrome_options =webdriver.ChromeOptions() chrome_options.add_argument('--proxy-server=http://'+ip) browser =webdriver.Chrome(chrome_options=chrome_options) browser.get('http://httpbin.org/get') time.sleep(5) |
运行结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多关注华科云商