對(duì)于反爬蟲(chóng)機(jī)制的處理,除了筆記2中偽造瀏覽器的方法,還可以使用代理IP和時(shí)間設(shè)置
一、代理IP
適用情況:限制IP地址情況,也可解決由于“頻繁點(diǎn)擊”而需要輸入驗(yàn)證碼登陸的情況。
這種情況最好的辦法就是維護(hù)一個(gè)代理IP池,網(wǎng)上有很多免費(fèi)的代理IP,良莠不齊,可以通過(guò)篩選找到能用的。對(duì)于“頻繁點(diǎn)擊”的情況,我們還可以通過(guò)限制爬蟲(chóng)訪(fǎng)問(wèn)網(wǎng)站的頻率來(lái)避免被網(wǎng)站禁掉。
這里推薦幾個(gè)IP免費(fèi)代理的網(wǎng)站:
(1) http://www.xicidaili.com/
(2) http://haoip.cc/tiqu.htm
對(duì)于requests方法:
import requests
#ip地址:端口號(hào)
proxies = {'http' : 'http://XX.XX.XX.XX:XXXX'}
#或者
proxies = {'http' : 'XX.XX.XX.XX:XXXX'}
response = requests.get(url=url, proxies=proxies)
我們實(shí)際應(yīng)用下,用站長(zhǎng)之家的查ip工具,看看實(shí)際ip到底有沒(méi)有進(jìn)行修改。
import requests
#一個(gè)能夠查當(dāng)前ip的網(wǎng)站
url = 'http://ip.chinaz.com/'
#用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)
對(duì)于urllib方法:
import urllib.request
#ip地址:端口號(hào)
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,此后調(diào)用urlopen()時(shí)都會(huì)使用安裝過(guò)的opener對(duì)象
urllib.request.install_opener(opener)
response = urllib.request.urlopen(url)
import urllib.request
url = 'http://ip.chinaz.com/'
proxies = {'http' : '218.86.128.100:8118'}
proxy_support = urllib.request.ProxyHandler(proxies)
#創(chuàng)建opener
opener = urllib.request.build_opener(proxy_support)
# 安裝opener,此后調(diào)用urlopen()時(shí)都會(huì)使用安裝過(guò)的opener對(duì)象
urllib.request.install_opener(opener)
response = urllib.request.urlopen(url)
html = response.read().decode('utf-8')
print(html)
我們可以看到,再返回的html中,我們的ip已經(jīng)發(fā)生了改變。

如果能多個(gè)ip隨機(jī)切換的話(huà),我們爬蟲(chóng)的強(qiáng)壯程度會(huì)更高,接下來(lái)簡(jiǎn)單說(shuō)說(shuō)隨機(jī)切換ip。
import random
#把我們從ip代理網(wǎng)站上得到的ip,用ip地址:端口號(hào)的格式存入iplist數(shù)組
iplist = ['XXX.XXX.XXX.XXX:XXXX', 'XXX.XXX.XXX.XXX:XXXX']
proxies ={'http': random.choice(iplist)}
二、時(shí)間設(shè)置
適用情況:限制頻率情況。
Requests,Urllib都可以使用time庫(kù)的sleep()函數(shù):
import time
time.sleep(1)#單位:秒
三、Timeout
timeout的設(shè)置,可以設(shè)置等待多久超時(shí),為了解決一些網(wǎng)站實(shí)在響應(yīng)過(guò)慢而造成的影響。
import requests
response = requests.get(url, timeout=10)
import urllib.request
response = urllib.request.urlopen(url, timeout=10)
四、異常處理
從requests的官方文檔我們看到:

簡(jiǎn)單地寫(xiě)個(gè)異常處理:
from requests.exceptions import RequestException
try:
XXXXX
except RequestException as e:
print('爬蟲(chóng)錯(cuò)誤,錯(cuò)誤原因:',e)