您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页python3的爬虫笔记5——代理IP和时间设置、异常处理

python3的爬虫笔记5——代理IP和时间设置、异常处理

来源:二三娱乐

对于反爬虫机制的处理,除了笔记2中伪造浏览器的方法,还可以使用代理IP和时间设置

一、代理IP
import requests
#ip地址:端口号
proxies = {'http' : 'http://XX.XX.XX.XX:XXXX'}
#或者
proxies = {'http' : 'XX.XX.XX.XX:XXXX'}
response = requests.get(url=url, proxies=proxies)
import requests
#一个能够查当前ip的网站
url = 
#用proxies字典保存代理ip
proxies = {'http' : '218.86.128.100:8118'}
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.103 Safari/537.36', 'Connection':'keep-alive'}
response = requests.get(url=url, proxies=proxies,headers=headers)
response.encoding = 'utf-8'
html = response.text
print(html)

对于urllib方法:

import urllib.request
#ip地址:端口号
proxies = {'http' : 'http://XX.XX.XX.XX:XXXX'}
#或者
proxies = {'http' : 'XX.XX.XX.XX:XXXX'}
proxy_support = urllib.request.ProxyHandler(proxies)
opener = urllib.request.build_opener(proxy_support)
# 安装opener,此后调用urlopen()时都会使用安装过的opener对象
urllib.request.install_opener(opener) 
response = urllib.request.urlopen(url)
import urllib.request
url = 
proxies = {'http' : '218.86.128.100:8118'}
proxy_support = urllib.request.ProxyHandler(proxies)
#创建opener
opener = urllib.request.build_opener(proxy_support)
# 安装opener,此后调用urlopen()时都会使用安装过的opener对象
urllib.request.install_opener(opener)
response = urllib.request.urlopen(url)
html = response.read().decode('utf-8')
print(html)

我们可以看到,再返回的html中,我们的ip已经发生了改变。

如果能多个ip随机切换的话,我们爬虫的强壮程度会更高,接下来简单说说随机切换ip。

import random
#把我们从ip代理网站上得到的ip,用ip地址:端口号的格式存入iplist数组
iplist = ['XXX.XXX.XXX.XXX:XXXX', 'XXX.XXX.XXX.XXX:XXXX']
proxies ={'http': random.choice(iplist)}
二、时间设置

适用情况:限制频率情况。
Requests,Urllib都可以使用time库的sleep()函数:

import time
time.sleep(1)#单位:秒
三、Timeout

timeout的设置,可以设置等待多久超时,为了解决一些网站实在响应过慢而造成的影响。

import requests
response =  requests.get(url, timeout=10)
import urllib.request
response =  urllib.request.urlopen(url, timeout=10)
四、异常处理

简单地写个异常处理:
from requests.exceptions import RequestException
try:
    XXXXX
except RequestException as e:
    print('爬虫错误,错误原因:',e)

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务