如何在python中仅用几行代码轻松获取代理的延迟?

How to easily obtain the latency of proxies with only a few lines of code in python?

我正在我的一个脚本中制作一些东西,它应该能够清除我所有缓慢的代理。代理在每一行上存储一个名为 proxies.txt 的文件。我希望能够使用变量指定以毫秒为单位的最大延迟。我在这里 Python requests find proxy latency 看到了类似的问题,但没有人回答。如果有办法做到这一点,请告诉我。

这不是您要求的 100% return是对还是错取决于代理是否及时响应

def ping(host):

    param = '-n' if platform.system().lower() == 'windows' else '-c'

    command = ['ping', param, '1', '-w', 250, '-n', '1', host]
    return subprocess.call(command, stdout=subprocess.PIPE) == 0

如果它在 250 毫秒内响应,那么 return 是一个布尔值(真或假)。我确信将其修改为 return 和 return 正确值很容易。然后,您需要做的就是将其放入文件中每一行的 for 循环中。此外,您还必须从代理测试中删除端口号和分号,然后重新附加它,我在这段代码中所做的是: 如果您想使用它,您必须更改它,因为它来自我编码的项目。

def check_proxies(filename):
    filename = str(filename)
    f = open(filename)
    lines = 0
    for _ in f:
        lines = lines + 1
    f.close()

    EstimatedTime = lines * config.Ping_Timeout
    print(f"{bcolors.Blue}Checking proxies... this will take at max {bcolors.OKGREEN}{EstimatedTime / 1000}{bcolors.Blue} seconds{bcolors.ENDC}")

    with open(filename) as f:
        workingProxies = []
        LineNum = 0
        for line in f.readlines():
            line = line.strip("\n").strip('\r')
            line = line.split(":")
            line_port = line[1]
            line_ip = line[0]
            if LineNum == 50:
                if config.extras.Proxy_Joke.Proxy_Joke_Extra:
                    Info.print_dad_joke()
                else:
                    pass
            LineNum = LineNum + 1
            if ping(line_ip):
                workingProxies = workingProxies + [f"{line_ip}:{line_port}"]
            else:
                pass
        if len(workingProxies) == 0:
            print("Error, no working proxies were detected, are you connected to the internet?")
    return workingProxies


def get_file_lines():
    InputProxies = 0
    with open(config.Proxy_File) as G:
        for _ in G.readlines():
            InputProxies = InputProxies + 1
    return InputProxies

我不知道我将如何做你想做的事,但这在我从事的项目中对我有用。