建立属于自己的代理IP池
python : 免费代理IP获取,验证可用性,建立属于自己的代理ip池

在进行爬虫爬取网站时候总会面临着各种各样的反爬措施,最让人头疼的一般就是封IP地址了,这时候使用代理IP就是一个明智的选择了。
建立属于自己的代理IP池是进行爬虫的一个很高效的办法。
网上存在着大量的免费代理IP网站,以下选取一个较为好用的代理IP网站进行爬取,建立属于自己的代理IP池。(西祠代理、快代理等等)
代码如下(获取西祠代理的可用高匿代理IP)
import requests,parsel,telnetlib
from fake_useragent import UserAgent
ua = UserAgent()
# 高匿代理网址 可以自行更换其他西祠代理网页内部
header = {"User-Agent":ua.random}
# 运行结果保存在代理txt文件中
url = "https://www.xicidaili.com/nn/"
seeeion = requests.session()
# 提取网页源代码
def request(url):
res = seeeion.get(url, headers=header)
html = parsel.Selector(res.text)
return html
# def test()
# 提取网页数据
def extract(html):
# 提取ID列表以及URL列表
id_list = html.xpath('//tr/td[2]/text()').extract()
post_list = html.xpath('//tr[@class]/td[3]/text()').extract()
print(len(id_list))
for id, post in zip(id_list, post_list):
try:
telnetlib.Telnet(id, post, timeout=5)
ip = id + ":" + post
print("通过第一关:",ip)
url = 'https://www.baidu.com'
response = requests.get(url,timeout=5, proxies={"https":ip})
if (response.status_code == 200):
print("通过第二关:",ip,"=================")
with open('F:\Python文件\代理IP\代理.txt', "a") as fp:
fp.write(ip + "\n")
# print("header : ", response.text)
except Exception as e:
pass
# print(e, '不可用')
# 在这里添加一个函数进行对IP检测,是否可用
print("完成")
try:
# 提取总页数
html = request(url)
page = html.xpath('//div[@class="pagination"]/a[10]/text()').extract_first()
page = int(page)
extract(html)
# 分页抓取
for i in list(range(2,4)): # 逐页发起请求 (page+1)
url1 = url + str(i)
html = request(url1)
extract(html)
except:
print("出现bug,请修改")