1. 程式人生 > 其它 >如何建立自己的代理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地址

方法一


F12進行除錯,頁面是靜態的頁面,結構也相對簡單,其IP地址全部在tr標籤

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


下面就直接爬蟲程式碼進行爬取

# 獲取開放代理介面
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就可以用別人的代理了