如何验证一批代理与某个URL的有效性?
我有一份包含100个代理的列表。我想要访问的网址是abc.com。我想检查有多少个代理能够成功获取这个网址,以及所花费的时间。我希望我说得清楚。我是个Python新手,想找一段代码来帮我。非常感谢任何帮助!:)
Proxies :
200.43.54.212
200.43.54.212
200.43.54.212
200.43.54.212
URL :
abc.com
Desired result :
Proxy isGood Time
200.43.54.112 n 23.12
200.43.54.222 n 12.34
200.43.54.102 y 11.09
200.43.54.111 y 8.85
补充说明:以上所有代理的端口都是80或8080。
1 个回答
4
你可以使用 urllib2 来获取网址。想要知道花了多少时间,可以用时间模块。下面是一个简单的例子,正好符合你的需求:
import urllib2
import time
def testProxies(url, proxies):
# prepare the request
req = urllib2.Request(url)
# run the request for each proxy
results = ["Proxy isGood Time"]
for proxy in (proxies):
# now set the proxy
req.set_proxy(proxy, "http")
# time it
start = time.time()
# try to open the URL
try:
urllib2.urlopen(req)
# format the results for success
results.append("%s y %.2f" % (proxy, time.time()-start))
except urllib2.URLError:
# format the results for failure
results.append("%s n %.2f" % (proxy, time.time()-start))
return results
testResults = testProxies("http://www.abc.com", ["200.43.54.112", "200.43.54.222",
"200.43.54.102", "200.43.54.111"])
for result in testResults:
print result
主要的要点是用 urllib2.Request(url)
创建请求,并使用 set_proxy()
函数,这样你就可以为请求设置一个代理。