如何建立自己的代理IP池,减少爬虫被封的几率

如何建立自己的代理IP池,减少爬虫被封的几率

在爬虫过程中,难免会遇到各种各样的反爬虫,运气不好,还会被对方网站给封了自己的IP,就访问不了对方的网站,爬虫也就凉凉。
《如何建立自己的代理IP池,减少爬虫被封的几率》

代理参数-proxies

首先我们先来介绍下什么是代理参数
代理,顾名思义,就是代理你原来的IP地址去对接网络
的IP地址
使用代理参数,可以隐藏自身真实的IP地址,避免被对方的网站封了。

1、语法结构
proxies = {
'协议':'协议://IP:端口号'
}
2、示例
proxies = {
'http':'http://IP:端口号',
'https':'https://IP:端口号'
}

如何获取代理IP

那具体如果获取代理IP呢,大多数IP都是收费,免费的IP的可以使用的很少,比如下面这些网站,

这次我就主要介绍爬取89网的免费IP,并测试可用性,存入自己的代理IP池中
89代理官网中有两种获取免费IP的方法,第一种就是主页面显示的IP地址

方法一

《如何建立自己的代理IP池,减少爬虫被封的几率》
F12进行调试,页面是静态的页面,结构也相对简单,其IP地址全部在tr标签
《如何建立自己的代理IP池,减少爬虫被封的几率》

import csv
import time ,random
import requests
from fake_useragent import UserAgent
from lxml import etree
class GetProxyIP(object):
	#初始化URL
    def __init__(self):
        self.url='https://www.89ip.cn/index_{}.html'
    # 获取代理IP
    def get_IP(self,url):
        html=requests.get(
            url=url,
            headers={
            'User-Agent':UserAgent().random
            },
            timeout=5
        ).text
        #转换为xpath可解析格式
        parse_html=etree.HTML(html)
        #解析得到所有tr列表
        tr_list=parse_html.xpath('//tr')
        #遍历每个tr,获取每个tr中的IP
        for tr in tr_list[1:]:
            ip=tr.xpath('.//td[1]/text()')[0].strip()
            port=tr.xpath('./td[2]/text()')[0].strip()
            #测试IP可用性
            self.mtest_ip(ip,port)

    def mtest_ip(self,ip,port):
        url='http://httpbin.org/get'
        #设置headers
        headers={
            'User-Agent':UserAgent().random
        }
        #设置proxies代理参数
        proxies={
            'http': f'http://{ip}:{port}',
            'https': f'https://{ip}:{port}'
        }
        try:
        	#发起请求
            res=requests.get(url=url,proxies=proxies,headers=headers,timeout=8)
            print(res.status_code)
            #得到状态码就说明IP可用
            if res.status_code:
                print(ip,port,'Sucess')
                #存到列表中
                L=[ip+':'+port]
                #写到csv中
                with open('proxies.csv', 'a', encoding='utf-8') as f:
                    writer=csv.writer(f)
                    writer.writerow(L)
        #IP不可用则抛出异常
        except Exception as e:
            print(ip,port,'Failed',e)
            
	#运行方法
    def main(self):
    	#爬取1000页
        for i in range(1,1001):
            url=self.url.format(i)
            #解析得到IP
            self.get_IP(url)
            time.sleep(random.randint(5,10))

if __name__ == '__main__':
    spider= GetProxyIP()
    spider.main()

方法二

在API接口中生成IP链接,访问进去也是有很多免费的代理IP
《如何建立自己的代理IP池,减少爬虫被封的几率》
《如何建立自己的代理IP池,减少爬虫被封的几率》
下面就直接爬虫代码进行爬取

# 获取开放代理接口
import csv

import requests
import re
from fake_useragent import UserAgent
# 获取代理IP列表
def get_ip_list():
    url='http://api.89ip.cn/tqdl.html?api=1&num=60&port=&address=&isp='
    html=requests.get(url=url,headers={'User-Agent':UserAgent().random}).text
    #按<br>分组
    t_arr=html.split('<br>')
    # 第一个特殊,需要先按</script>\n分组
    t_0=t_arr[1].split('</script>\n')[1].strip
    ip_list=[]
    ip_list.append(t_0)
    # 第二个及后面直接遍历就行
    for i in range(2,len(t_arr)-1):
        ip_list.append(t_arr[i])
    print(ip_list)
    #测试所有的IP可用性
    for ip in ip_list:
        mtest_ip(ip)
def mtest_ip(ip):
    url='http://baidu.com/'
    headers={
        'User-Agent':UserAgent().random
    }
    proxies={
        'http': f'http://{ip}',
        'https': f'https://{ip}'
    }
    try:
        res=requests.get(url=url,proxies=proxies,headers=headers,timeout=8)
        print(res.status_code)
        #一般状态码返回200就说明可用
        if res.status_code==200:
            print(ip,'Sucess')
            L=[ip]
            with open('proxies2.csv', 'a', encoding='utf-8', newline='') as f:
                writer=csv.writer(f)
                writer.writerow(L)
    except Exception as e:
        print(ip,'Failed',e)

if __name__ == '__main__':
    get_ip_list()

以后直接调用IP就可以用别人的代理了

    原文作者:冰山一树Sankey
    原文地址: https://blog.csdn.net/m0_59464010/article/details/123202361
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞