python爬虫数据采集ip被封一篇解决

代理服务的介绍:
我们在做爬虫的过程中经常最初爬虫都正常运行,正常爬取数据,一切看起来都是美好,然而一杯茶的功夫就出现了错误。
如:403 Forbidden错误,“您的IP访问频率太高”错误,或者跳出一个验证码让我们输入,之后解封,但过一会又出现类似情况。
出现这个现象的原因是因为网站采取了一些反爬中措施,如:服务器检测IP在单位时间内请求次数超过某个阀值导致,称为封IP。
为了解决此类问题,代理就派上了用场,如:代理软件、付费代理、ADSL拨号代理,以帮助爬虫脱离封IP的苦海。
测试HTTP请求及响应的网站:http://httpbin.org/
GET地址 :http://httpbin.org/get
POST地址:http://httpbin.org/post
httpbin这个网站能测试 HTTP 请求和响应的各种信息,比如 cookie、ip、headers 和登录验证等.
且支持 GET、POST 等多种方法,对 web 开发和测试很有帮助。
代理的设置:
① urllib的代理设置
from urllib.error import URLError
from urllib.request import ProxyHandler, build_opener​proxy = '127.0.0.1:8888'#需要认证的代理#proxy = 'username:password@127.0.0.1:8888'​#使用ProxyHandler设置代理proxy_handler = ProxyHandler({ 'http': 'http://' + proxy, 'https': 'https://' + proxy})#传入参数创建Opener对象opener = build_opener(proxy_handler)try: response = opener.open('http://httpbin.org/get') print(response.read().decode('utf-8'))except URLError as e: print(e.reason)

  

② requests的代理设置
import requests
​proxy = '127.0.0.1:8888'#需要认证的代理#proxy = 'username:password@127.0.0.1:8888'​proxies = { 'http': 'http://' + proxy, 'https': 'https://' + proxy,}try: response = requests.get('http://httpbin.org/get', proxies=proxies) print(response.text)except requests.exceptions.ConnectionError as e: print('Error', e.args)

 

③ Selenium的代理使用
使用的是PhantomJS
from selenium import webdriver
​service_args = [ '--proxy=127.0.0.1:9743', '--proxy-type=http', #'--proxy-auth=username:password' #带认证代理]​browser = webdriver.PhantomJS(service_args=service_args)browser.get('http://httpbin.org/get')print(browser.page_source)
使用的是Chrome
from selenium import webdriver
​proxy = '127.0.0.1:9743'chrome_options = webdriver.ChromeOptions()chrome_options.add_argument('--proxy-server=http://' + proxy)chrome = webdriver.Chrome(chrome_options=chrome_options)chrome.get('http://httpbin.org/get')

 

④ 在Scrapy使用代理
#在Scrapy的Downloader Middleware中间件里
... def process_request(self, request, spider): request.meta['proxy'] = 'http://127.0.0.1:9743' ...

免费代理IP的使用

我们可以从互联网中获取免费的代理IP:
import requests,random
​#定义代理池proxy_list = [ '182.39.6.245:38634', '115.210.181.31:34301', '123.161.152.38:23201', '222.85.5.187:26675', '123.161.152.31:23127',]​# 随机选择一个代理proxy = random.choice(proxy_list)​proxies = { 'http': 'http://' + proxy, 'https': 'https://' + proxy,}try: response = requests.get('http://httpbin.org/get', proxies=proxies) print(response.text)except requests.exceptions.ConnectionError as e: print('Error', e.args)

 

收费代理IP的使用
收费代理还是很多的如:
芝麻代理
极光代理
太阳代理
在requests中使用收费代理
import requests
​# 从代理服务中获取一个代理IPproxy = requests.get("http://tvp.daxiangdaili.com/ip/?tid=559775358931681&num=1").textproxies = { 'http': 'http://' + proxy, 'https': 'https://' + proxy,}try: response = requests.get('http://httpbin.org/get', proxies=proxies) print(response.text)except requests.exceptions.ConnectionError as e: print('Error', e.args)

 

 

posted @ 2020-09-10 15:26  亚洲小番茄  阅读(998)  评论(0编辑  收藏  举报