Python:urllib2和代理

时间:2013-01-05 18:46:43

标签: python proxy urllib2

我正在尝试在Python中编写一个脚本,使用代理列表每隔x秒重新加载一个页面,我现在遇到了问题。我知道这也不是代理人的错,因为我可以ping他们并且他们返回正常。它们是HTTP代理。我的脚本将此错误返回给我:

urllib.error.URLError: <urlopen error [WinError 10061] No connection could be made because the target machine actively refused it>

我不知道如何修复它。这是实际的脚本:

import urllib.request
import time
proxy_list = input("Name of proxy list file?: ")
proxy_file = open(proxy_list, 'r')
url = input("URL to bot? (Has to include http://): ")
sleep = float(input("Time between reloads? (In seconds, 0 for none): "))
proxies = []
for line in proxy_file:
    proxies.append( line )
proxies = [w.replace('\n', '') for w in proxies]

while True:
    for i in range(len(proxies)):
        proxy = proxies[i]
        proxy2 = {"http":"http://%s" % proxy}
        proxy_support = urllib.request.ProxyHandler(proxy2)

        opener = urllib.request.build_opener(proxy_support)
        urllib.request.install_opener(opener)
        urllib.request.urlopen(url).read()
        time.sleep(float(sleep))

感谢。

1 个答案:

答案 0 :(得分:2)

请勿使用urllib2。说真的,就是不要。

你的圣杯:requests

你要做的是:

while True:
    for proxy in proxies:
        r = request.get(my_url, proxies={'http': proxy})
        print r.text
        time.sleep(float(sleep))