gpt4 book ai didi

python - 如果主机5秒内没有响应如何关闭连接

转载 作者:行者123 更新时间:2023-12-01 09:17:52 24 4
gpt4 key购买 nike

我正在尝试编写程序,该程序将检查哪些代理处于事件状态。当我的脚本尝试连接到非事件代理时,甚至需要大约 30 秒。当我检查数千个代理的列表时,脚本的工作时间增加了几个小时。

如果响应时间超过5秒,是否可以破坏此功能?

def get(url, proxy):
proxies = {
'http': 'http://'+proxy,
'https': 'https://'+proxy
}
s = requests.Session()
s.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
s.proxies = proxies
r = s.get(url)
return [r.status_code, r.reason, r.text]

with open('proxy.txt') as ips:
for ip in ips:
ip = ip.split('\n', 1)[0]
try:
get(url, ip)
with open('working.txt', 'a') as the_file:
the_file.write(ip+'\n')
except:
print("error")

谢谢。

最佳答案

timeout kwarg与s.get结合使用。 s.get(url, timeout=5)

关于python - 如果主机5秒内没有响应如何关闭连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51068022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com