代理地址最后验证日期:2021-11-09

纯真

66免费代理网 #推荐

西刺免费代理IP

酷伯伯HTTP代理

快代理 #推荐

全网代理IP

IP海

360代理IP

流年免费HTTP代理IP 24小时自助提取系统 #推荐

云代理

代理IP检测平台,100免费代理IP

瑶瑶代理IP

蚂蚁代理

开心代理

讯代理

转载于:https://www.cnblogs.com/hankleo/p/9683671.html

但是很多时候在开发过程中很少开发者,会使用复制粘贴的形式将代理ip保存到一个列表里面。

直接存到列表的方式好处是直接方便。缺点也很明显:1.可使用的ip有限。2.代理ip也会面临失效的可能。

在我实际的开发测试使用的时候,个人更偏向于实时爬取有效的代理ip做爬虫。下面将使用快代理作为例子。

import time
import requests
import random
from bs4 import BeautifulSoup

IP_POOL = []
def get_max_proxy():
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36",
        "Host": "www.kuaidaili.com",
        "origin": "https://www.kuaidaili.com"
    }
    html = requests.get(url="https://www.kuaidaili.com/free/inha/1/", headers=headers).text
    soup = BeautifulSoup(html,"lxml")
    div = soup.find_all(name="div",attrs={"id":"listnav"})
    max = 1
    for d in div:
        for num in d.find_all(name="a"):
            if int(num.text) > max:max = int(num.text)
    return max

def get_proxy_list(max):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36",
        "Host": "www.kuaidaili.com",
        "origin": "https://www.kuaidaili.com"
    }
    for i in range(1,max):
        if i>3:return IP_POOL#调试限制使用3个
        time.sleep(0.2*random.randint(1,5))
        html = requests.get(url="https://www.kuaidaili.com/free/inha/{}/".format(i), headers=headers).text
        soup = BeautifulSoup(html,"lxml")
        tbody =soup.find_all(name="tbody")
        for tb in tbody:
            for t in tb.find_all(name="td",attrs={"data-title":"IP"}):
                IP_POOL.append(t.text)
    return IP_POOL

max=get_max_proxy()
IP_POOL=get_proxy_list(max)
print(len(IP_POOL))
print(IP_POOL)

 

posted on 2021-11-10 00:10  topass123  阅读(962)  评论(0编辑  收藏  举报