最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

用python構(gòu)建IP代理池詳解

 更新時(shí)間:2022年01月19日 11:07:16   作者:A-L-Kun  
大家好,本篇文章主要講的是用python構(gòu)建IP代理池詳解,感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下

概述

用爬蟲時(shí),大部分網(wǎng)站都有一定的反爬措施,有些網(wǎng)站會(huì)限制每個(gè) IP 的訪問速度或訪問次數(shù),超出了它的限制你的 IP 就會(huì)被封掉。對(duì)于訪問速度的處理比較簡(jiǎn)單,只要間隔一段時(shí)間爬取一次就行了,避免頻繁訪問;而對(duì)于訪問次數(shù),就需要使用代理 IP 來幫忙了,使用多個(gè)代理 IP 輪換著去訪問目標(biāo)網(wǎng)址可以有效地解決問題。

目前網(wǎng)上有很多的代理服務(wù)網(wǎng)站提供代理服務(wù),也提供一些免費(fèi)的代理,但可用性較差,如果需求較高可以購(gòu)買付費(fèi)代理,可用性較好。

因此我們可以自己構(gòu)建代理池,從各種代理服務(wù)網(wǎng)站中獲取代理 IP,并檢測(cè)其可用性(使用一個(gè)穩(wěn)定的網(wǎng)址來檢測(cè),最好是自己將要爬取的網(wǎng)站),再保存到數(shù)據(jù)庫(kù)中,需要使用的時(shí)候再調(diào)用。

提供免費(fèi)代理的網(wǎng)站

廠商名稱地址
66代理http://www.66ip.cn/
西刺代理https://www.xicidaili.com
全網(wǎng)代理http://www.goubanjia.com
云代理http://www.ip3366.net
IP海http://www.iphai.com
快代理https://www.kuaidaili.com
免費(fèi)代理IP庫(kù)http://ip.jiangxianli.com
小幻代理https://ip.ihuan.me/

代碼

導(dǎo)包

import loguru, requests, random, time  # 發(fā)送請(qǐng)求,記錄日志,等
from lxml import etree  # 分析數(shù)據(jù)
from concurrent.futures import ThreadPoolExecutor  # 線程池

網(wǎng)站頁(yè)面的url

由于小幻代理的每個(gè)頁(yè)面的url沒有規(guī)律,所以需要一一獲取

def get_url():  # 得到存放ip地址的網(wǎng)頁(yè)
    print("正在獲取ip池", ",不要著急!")
    for i in range(random.randint(10, 20)):  # 爬取隨機(jī)頁(yè)數(shù)
        time.sleep(1)
        if i == 0:
            url = "https://ip.ihuan.me/"
        else:
            url = url_list[-1]
        try:
            resp = requests.get(url=url, headers=headers_test, timeout=10)
        except Exception as e:
            print(e)
            break
        html = etree.HTML(resp.text)
        ul = html.xpath('//ul[@class="pagination"]')
        ul_num = html.xpath('//ul[@class="pagination"]/li')
        for j in range(len(ul_num)):
            if j != 0 and j != len(ul_num) - 1:
                a = ul[0].xpath(f"./li[{j}+1]/a/@href")[0]
                url_list.append("https://ip.ihuan.me/" + a)  # 得到許多的代理ip網(wǎng)址
        loguru.logger.info(f"over,{url}")

ip地址

def get_ip():
    for i in url_list:
        time.sleep(1)
        resp = requests.get(url=i, headers=headers)
        html = etree.HTML(resp.text)
        td = html.xpath("http://tbody/tr")
        for i in td:
            ip = i.xpath("./td[1]//text()")[0]  # 地址
            pt = i.xpath("./td[2]//text()")[0]  # 端口
            tp = "http" if i.xpath("./td[5]//text()")[0] == "不支持" else "https"  # 訪問類型
            ip_list.append({"type": tp, "proxy": f"{ip}:{pt}"})
    loguru.logger.info("ip地址獲取完成")

檢測(cè)

def test_ip(ip):
    proxy_test = {
        "http": f"{ip}",
        "https": f"{ip}"
        # 注意:如果請(qǐng)求的ip是https類型的,但代理的ip是只支持http的,那么還是使用本機(jī)的ip,如果請(qǐng)求的ip是http類型的,那么代理的ip一定要是http的,前面不能寫成https,否則使用本機(jī)IP地址
    }
    resp = requests.get(url=url_test, headers=headers, proxies=proxy_test, timeout=6)
    if resp.json()["origin"] == ip.split(":")[0]:
        ip = {"type": url.strip(":")[0], "proxy": ip}  # 格式化ip,便于后期處理,是的其有http/https標(biāo)識(shí)
        temp_ip.append(ip)  # 符合條件的添加,不符合條件的拋棄

整理

def set_ip(url) -> "動(dòng)態(tài)構(gòu)建ip池":  # 要傳入需要爬取網(wǎng)頁(yè)的url
    try:
        f = open('./app/ip.txt', "r")
        for j in eval(f.read()):
            temp_ip.append(j)
        f.close()
    except Exception as e:
        print("沒有ip,正在構(gòu)造ip池,請(qǐng)稍等")

    if not temp_ip:  # 判斷是否有ip地址
        print("沒有ip地址,正在獲取")
        get_url()
    else:
        for i in temp_ip:
            ip_list.append(i)  # 將已有的ip添加到測(cè)試ip中
        temp_ip.clear()

    get_ip()  # 得到大量ip地址
    with open('./app/ip.txt', "w") as file:
        file.write(ip_list)
    ip_able = list(set(j["proxy"] for j in ip_list if j["type"] == url.split(":")[0]))  # 存放符合要求的ip字符串,同時(shí)利用字典去重
    url_test = "http://httpbin.org/ip" if url.split(":")[0] == "http" else ""  # 測(cè)試ip地址是否有用

    def test_ip(ip):
        proxy_test = {
            "http": f"{ip}",
            "https": f"{ip}"
            # 注意:如果請(qǐng)求的ip是https類型的,但代理的ip是只支持http的,那么還是使用本機(jī)的ip,如果請(qǐng)求的ip是http類型的,那么代理的ip一定要是http的,前面不能寫成https,否則使用本機(jī)IP地址
        }
        resp = requests.get(url=url_test, headers=headers, proxies=proxy_test, timeout=6)
        if resp.json()["origin"] == ip.split(":")[0]:
            ip = {"type": url.strip(":")[0], "proxy": ip}  # 格式化ip,便于后期處理,是的其有http/https標(biāo)識(shí)
            temp_ip.append(ip)  # 符合條件的添加,不符合條件的拋棄

    with ThreadPoolExecutor(50) as pool:  # 使用多線程測(cè)試
        pool.map(test_ip, ip_able)

    pool.join()

    print("測(cè)試完畢")

    if temp_ip:
        i = random.choice(temp_ip)
        proxy = {
            "http": f"{i['proxy']}",
            "https": f"{i['proxy']}"
        }
        return proxy
    else:
        set_ip(url=url)

必要參數(shù)

# 參數(shù)

headers = {
    'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
}
headers_test = {
    'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36",
    "accept-encoding": "gzip, deflate, br",
    "cookie": "Hm_lvt_8ccd0ef22095c2eebfe4cd6187dea829=1642389014,1642412091",
    "Referer": "https://ip.ihuan.me/"
}
url_list, ip_list, temp_ip = ["https://ip.ihuan.me/"], [], []  # 存放url, 存放ip地址, 有用的ip地址

總代碼

import loguru, requests, random, time
from lxml import etree
from concurrent.futures import ThreadPoolExecutor


def get_url():  # 得到存放ip地址的網(wǎng)頁(yè)
    print("正在獲取ip池", ",不要著急!")
    for i in range(random.randint(10, 20)):  # 爬取隨機(jī)頁(yè)數(shù)
        time.sleep(1)
        if i == 0:
            url = "https://ip.ihuan.me/"
        else:
            url = url_list[-1]
        try:
            resp = requests.get(url=url, headers=headers_test, timeout=10)
        except Exception as e:
            print(e)
            break
        html = etree.HTML(resp.text)
        ul = html.xpath('//ul[@class="pagination"]')
        ul_num = html.xpath('//ul[@class="pagination"]/li')
        for j in range(len(ul_num)):
            if j != 0 and j != len(ul_num) - 1:
                a = ul[0].xpath(f"./li[{j}+1]/a/@href")[0]
                url_list.append("https://ip.ihuan.me/" + a)  # 得到許多的代理ip網(wǎng)址
        loguru.logger.info(f"over,{url}")


def get_ip():
    for i in url_list:
        time.sleep(1)
        resp = requests.get(url=i, headers=headers)
        html = etree.HTML(resp.text)
        td = html.xpath("http://tbody/tr")
        for i in td:
            ip = i.xpath("./td[1]//text()")[0]  # 地址
            pt = i.xpath("./td[2]//text()")[0]  # 端口
            tp = "http" if i.xpath("./td[5]//text()")[0] == "不支持" else "https"  # 訪問類型
            ip_list.append({"type": tp, "proxy": f"{ip}:{pt}"})
    loguru.logger.info("ip地址獲取完成")


def set_ip(url) -> "動(dòng)態(tài)構(gòu)建ip池":  # 要傳入需要爬取網(wǎng)頁(yè)的url
    try:
        f = open('./app/ip.txt', "r")
        for j in eval(f.read()):
            temp_ip.append(j)
        f.close()
    except Exception as e:
        print("沒有ip,正在構(gòu)造ip池,請(qǐng)稍等")

    if not temp_ip:  # 判斷是否有ip地址
        print("沒有ip地址,正在獲取")
        get_url()
    else:
        for i in temp_ip:
            ip_list.append(i)  # 將已有的ip添加到測(cè)試ip中
        temp_ip.clear()

    get_ip()  # 得到大量ip地址
    with open('./app/ip.txt', "w") as file:
        file.write(ip_list)
    ip_able = list(set(j["proxy"] for j in ip_list if j["type"] == url.split(":")[0]))  # 存放符合要求的ip字符串,同時(shí)利用集合去重
    url_test = "http://httpbin.org/ip" if url.split(":")[0] == "http" else ""  # 測(cè)試ip地址是否有用

    def test_ip(ip):
        proxy_test = {
            "http": f"{ip}",
            "https": f"{ip}"
            # 注意:如果請(qǐng)求的ip是https類型的,但代理的ip是只支持http的,那么還是使用本機(jī)的ip,如果請(qǐng)求的ip是http類型的,那么代理的ip一定要是http的,前面不能寫成https,否則使用本機(jī)IP地址
        }
        resp = requests.get(url=url_test, headers=headers, proxies=proxy_test, timeout=6)
        if resp.json()["origin"] == ip.split(":")[0]:
            ip = {"type": url.strip(":")[0], "proxy": ip}  # 格式化ip,便于后期處理,是的其有http/https標(biāo)識(shí)
            temp_ip.append(ip)  # 符合條件的添加,不符合條件的拋棄

    with ThreadPoolExecutor(50) as pool:  # 使用多線程測(cè)試
        pool.map(test_ip, ip_able)

    pool.join()

    print("測(cè)試完畢")

    if temp_ip:
        i = random.choice(temp_ip)
        proxy = {
            "http": f"{i['proxy']}",
            "https": f"{i['proxy']}"
        }
        return proxy
    else:
        set_ip(url=url)


# 參數(shù)

headers = {
    'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
}
headers_test = {
    'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36",
    "accept-encoding": "gzip, deflate, br",
    "cookie": "Hm_lvt_8ccd0ef22095c2eebfe4cd6187dea829=1642389014,1642412091",
    "Referer": "https://ip.ihuan.me/"
}
url_list, ip_list, temp_ip = ["https://ip.ihuan.me/"], [], []  # 存放url, 存放ip地址, 有用的ip地址

if __name__ == '__main__':
    proxy = set_ip(url="https://www.baidu.com")  # 得到代理ip
    print(proxy)

總結(jié)

如果安裝了數(shù)據(jù)庫(kù)的話,可以使用數(shù)據(jù)庫(kù)存儲(chǔ)得到的ip,代碼中使用的是本地的文件存儲(chǔ)數(shù)據(jù),同時(shí),要盡量避免本機(jī)ip被封

到此這篇關(guān)于用python構(gòu)建IP代理池詳解的文章就介紹到這了,更多相關(guān)python IP代理池詳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python中的生成器和yield詳細(xì)介紹

    Python中的生成器和yield詳細(xì)介紹

    這篇文章主要介紹了Python中的生成器和yield詳細(xì)介紹,本文講解了列表推導(dǎo)與生成器表達(dá)式、斐波那契數(shù)列、生成器Generator、協(xié)程與yield表達(dá)式、使用生成器與協(xié)程等內(nèi)容,需要的朋友可以參考下
    2015-01-01
  • Python基于DES算法加密解密實(shí)例

    Python基于DES算法加密解密實(shí)例

    這篇文章主要介紹了Python基于DES算法加密解密實(shí)現(xiàn)方法,以實(shí)例形式分析了DES算法實(shí)現(xiàn)加密解密的相關(guān)技巧,需要的朋友可以參考下
    2015-06-06
  • 關(guān)于Python參數(shù)解析器argparse的應(yīng)用場(chǎng)景

    關(guān)于Python參數(shù)解析器argparse的應(yīng)用場(chǎng)景

    這篇文章主要介紹了關(guān)于Python參數(shù)解析器argparse的應(yīng)用場(chǎng)景,argparse 模塊使編寫用戶友好的命令行界面變得容易,程序定義了所需的參數(shù),而 argparse 將找出如何從 sys.argv 中解析這些參數(shù),需要的朋友可以參考下
    2023-08-08
  • Python設(shè)置matplotlib.plot的坐標(biāo)軸刻度間隔以及刻度范圍

    Python設(shè)置matplotlib.plot的坐標(biāo)軸刻度間隔以及刻度范圍

    這篇文章主要介紹了Python設(shè)置matplotlib.plot的坐標(biāo)軸刻度間隔以及刻度范圍,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-06-06
  • python開發(fā)利器之ulipad的使用實(shí)踐

    python開發(fā)利器之ulipad的使用實(shí)踐

    Ulipad是一個(gè)國(guó)人limodou編寫的專業(yè)Python編輯器,它基于wxpython開發(fā)的GUI(圖形化界面)。下面這篇文章主要介紹了python開發(fā)利器之ulipad的使用實(shí)踐,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來一起看看吧。
    2017-03-03
  • Python編程之順序執(zhí)行與程序的主入口詳解

    Python編程之順序執(zhí)行與程序的主入口詳解

    程序從程序入口進(jìn)入,到程序執(zhí)行結(jié)束,大體是按照順序結(jié)構(gòu)執(zhí)行語(yǔ)句、函數(shù)或代碼塊,掌握程序的結(jié)構(gòu),有利于把握程序的主體框架,下面這篇文章主要給大家介紹了關(guān)于Python編程之順序執(zhí)行與程序的主入口的相關(guān)資料,需要的朋友可以參考下
    2022-12-12
  • 通過PYTHON來實(shí)現(xiàn)圖像分割詳解

    通過PYTHON來實(shí)現(xiàn)圖像分割詳解

    這篇文章主要介紹了通過PYTHON來實(shí)現(xiàn)圖像分割詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,,需要的朋友可以參考下
    2019-06-06
  • Python爬蟲爬取有道實(shí)現(xiàn)翻譯功能

    Python爬蟲爬取有道實(shí)現(xiàn)翻譯功能

    這篇文章主要介紹了Python爬蟲爬取有道實(shí)現(xiàn)翻譯功能,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-11-11
  • Django使用redis緩存服務(wù)器的實(shí)現(xiàn)代碼示例

    Django使用redis緩存服務(wù)器的實(shí)現(xiàn)代碼示例

    這篇文章主要介紹了Django使用redis緩存服務(wù)器的實(shí)現(xiàn)代碼示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • python?sklearn數(shù)據(jù)預(yù)處理之?dāng)?shù)據(jù)縮放詳解

    python?sklearn數(shù)據(jù)預(yù)處理之?dāng)?shù)據(jù)縮放詳解

    數(shù)據(jù)的預(yù)處理是數(shù)據(jù)分析,或者機(jī)器學(xué)習(xí)訓(xùn)練前的重要步驟,這篇文章主要為大家詳細(xì)介紹了sklearn數(shù)據(jù)預(yù)處理中數(shù)據(jù)縮放的相關(guān)知識(shí),感興趣的小伙伴可以學(xué)習(xí)一下
    2023-10-10

最新評(píng)論

成武县| 西峡县| 四子王旗| 綦江县| 吉安市| 福泉市| 静乐县| 大城县| 齐齐哈尔市| 五常市| 鄱阳县| 邵阳县| 民权县| 广饶县| 曲阜市| 禹州市| 浦东新区| 鞍山市| 景谷| 和静县| 荥经县| 确山县| 清苑县| 西乡县| 文昌市| 天台县| 赤城县| 惠东县| 辉南县| 雷波县| 珲春市| 潼南县| 榆社县| 子长县| 梅河口市| 都江堰市| 调兵山市| 扶绥县| 三河市| 连城县| 临潭县|