1.用户代理池
将多个用户代理组建为一个池子,在访问的时候每次使用不同的用户代理。
1.1构造方法
借助urllib.request、re、random模块:
import urllib.request
import re
import random
uapools=[
'User-Agent值'
'User-Agent值'
'User-Agent值'
···
]
def ua(uapools):
thisua=random.choice(uapools)
print(thisua)
headers=('User-Agent',thisua)
opener=urllib.request.build_opener()
opener.addheaders=[headers]
urllib.request.install_opener(opener)#安装为全局
不同的User-Agent值可以通过不同的浏览器以不同的方式打开不同网页来获取。位置还是在开发者工具里的网络里。
2.IP代理与IP代理池
IP代理:
IP代理:让爬虫使用代理IP去去爬取网站。
以下代码是可以正常运行的,如果IP失效,替换IP即可。
import urllib.request
ip='47.100.21.174:8021'
proxy=urllib.request.ProxyHandler({'http':ip})
opener=urllib.request.build_opener(proxy,urllib.request.HTTPHandler)
headers=('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0')
opener.addheaders=[headers]
urllib.request.install_opener(opener)#安装为全局
url='http://www.baidu.com'
data=urllib.request.urlopen(url).read().decode('utf-8','ignore')
print(data)
IP代理池:
以下为运行代码,是以上两种方法的结合:
import random
import urllib.request
ippools=[
'134.175.55.15:8888',
'175.44.151.130:9000',
'117.90.252.170:9000',
'124.94.196.81:9999',
'183.161.29.127:8060',
]
def ip(ippools):
thisip=random.choice(ippools)
print(thisip)
proxy = urllib.request.ProxyHandler({'http': thisip})
opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)
headers = ('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0')
opener.addheaders = [headers]
for x in range(0,len(ippools)):
print(x)
try:
url = 'http://www.baidu.com'
urllib.request.install_opener(opener) # 安装为全局
data = urllib.request.urlopen(url).read().decode('utf-8', 'ignore')
print(data)
except Exception as err:
print(err)
ip(ippools)
使用API接口调用:
适用于IP不稳定的情形。
import urllib.request
def ip():
thisip = urllib.request.urlopen('API接口').read()
print(thisip)
proxy = urllib.request.ProxyHandler({'http': thisip})
opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)
headers = ('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0')
opener.addheaders = [headers]
urllib.request.install_opener(opener) # 安装为全局
for x in range(0, 999999999):
ip()
print(x)
try:
url = 'http://www.baidu.com'
data = urllib.request.urlopen(url).read().decode('utf-8', 'ignore')
print(data)
except Exception as err:
print(err)
总结:
爬虫在爬取目标网站时,重复而大量的访问,会使目标服务器察觉并进行封禁,通过用户代理和IP代理两种方式进行伪装,可以有避免目标服务器封禁而造成的无法爬取,两种方式可以混合使用,将用户代理和IP代理混合,增强自身的伪装能力。采用API接口的方法可以通过大量获取IP解决IP不稳定的问题。