设置代理IP的原因
如果我们使用Python爬虫爬取一个网站时,并且需要频繁访问该网站。假如一个网站它会检测某一段时间某个IP的访问次数,如果访问次数过多,它会禁止你的访问。所以你可以设置一些代理服务器来帮助你做工作,每隔一段时间换一个代理,这样便不会出现因为频繁访问而导致禁止访问的现象。
方案一:获取代理IP列表
这里以西刺代理IP为例(网站链接),免费和方便爬取以获取IP
是它的优点。
示例代码:
# 仅爬取西刺代理首页IP地址
from bs4 import BeautifulSoup
from urllib.request import urlopen
from urllib.request import Request
def get_ip_list(obj):
ip_text = obj.findAll('tr', {'class': 'odd'}) # 获取带有IP地址的表格的所有行
ip_list = []
for i in range(len(ip_text)):
ip_tag = ip_text[i].findAll('td')
ip_port = ip_tag[1].get_text() + ':' + ip_tag[2].get_text() # 提取出IP地址和端口号
ip_list.append(ip_port)
print("共收集到了{}个代理IP".format(len(ip_list)))
print(ip_list)
return ip_list
if __name__ == '__main__':
url = 'http://www.xicidaili.com/'
headers = {
'User-Agent': 'User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36'}
request = Request(url, headers=headers)
response = urlopen(request)
bsObj = BeautifulSoup(response, 'lxml') # 解析获取到的html
get_ip_list(bsObj)
运行结果:
Running E:/Python_Test/Spider_Test/Cuiqingcai/Proxy_Test.py
共收集到了50个代理IP
['101.68.73.54:53281', '120.38.65.169:22166', '182.88.123.170:8123', '61.135.217.7:80', '120.76.55.49:8088', '182.90.100.76:8123', '220.166.242.180:8118', '110.73.4.165:8123', '115.46.72.238:8123', '61.145.49.144:808', '218.56.132.155:8080', '182.88.122.150:9797', '61.155.164.108:3128', ......]
方案二:随机获取一个代理IP
根据方案一的代码修改而来,运行下面代码可以随机获取一个西刺代理中的代理IP
,以键值对形式返回。
示例代码:
from bs4 import BeautifulSoup
from urllib.request import urlopen
from urllib.request import Request
def get_ip_list(obj):
ip_text = obj.findAll('tr', {'class': 'odd'})
ip_list = []
for i in range(len(ip_text)):
ip_tag = ip_text[i].findAll('td')
ip_port = ip_tag[1].get_text() + ':' + ip_tag[2].get_text()
ip_list.append(ip_port)
# print("共收集到了{}个代理IP".format(len(ip_list)))
# print(ip_list)
return ip_list
def get_random_ip(bsObj):
ip_list = get_ip_list(bsObj)
import random
random_ip = 'http://' + random.choice(ip_list)
proxy_ip = {'http:': random_ip}
return proxy_ip
if __name__ == '__main__':
url = 'http://www.xicidaili.com/'
headers = {
'User-Agent': 'User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36'}
request = Request(url, headers=headers)
response = urlopen(request)
bsObj = BeautifulSoup(response, 'lxml')
random_ip = get_random_ip(bsObj)
print(random_ip) # 打印出获取到的随机代理IP
运行结果:
Running E:/Python_Test/Spider_Test/Cuiqingcai/Proxy_Test.py
{'http:': 'http://116.28.106.165:6666'}