2010-07-02 8 views
15

Ho questo programma che controlla un sito web, e voglio sapere come posso controllare tramite delega in Python ...Come posso aprire un sito Web con urllib tramite proxy in Python?

Questo è il codice, solo per esempio

while True: 
    try: 
     h = urllib.urlopen(website) 
     break 
    except: 
     print '['+time.strftime('%Y/%m/%d %H:%M:%S')+'] '+'ERROR. Trying again in a few seconds...' 
     time.sleep(5) 
+0

urllib2 http://stackoverflow.com/questions/1450132/proxy-with-urllib2 –

risposta

29

Per impostazione predefinita, urlopen usa la variabile d'ambiente http_proxy per determinare quale proxy HTTP da utilizzare:

$ export http_proxy='http://myproxy.example.com:1234' 
$ python myscript.py # Using http://myproxy.example.com:1234 as a proxy 

Se invece desidera specificare un proxy all'interno della vostra applicazione, si può dare un ar proxies gument a urlopen:

proxies = {'http': 'http://myproxy.example.com:1234'} 
print "Using HTTP proxy %s" % proxies['http'] 
urllib.urlopen("http://www.google.com", proxies=proxies) 

Edit: Se ho capito bene i vostri commenti, si vuole provare diverse deleghe e stampare ogni proxy come si prova. Che ne dici di questo?

candidate_proxies = ['http://proxy1.example.com:1234', 
        'http://proxy2.example.com:1234', 
        'http://proxy3.example.com:1234'] 
for proxy in candidate_proxies: 
    print "Trying HTTP proxy %s" % proxy 
    try: 
     result = urllib.urlopen("http://www.google.com", proxies={'http': proxy}) 
     print "Got URL using proxy %s" % proxy 
     break 
    except: 
     print "Trying next proxy in 5 seconds" 
     time.sleep(5) 
+0

utilizzando l'esempio, come posso stampare quale proxy sta utilizzando nel momento in cui si verifica l'urlopen? – Shady

+0

@Shady: basta inserire un'istruzione 'print' che stampa il valore di' proxy ['http'] '. Dai un'occhiata al mio esempio aggiornato per vedere come potrebbe essere fatto. –

+0

ok grazie, ma se voglio più proxy, come, tonnellate di esso, ad esempio 10 proxy, aprendo uno prima del prossimo – Shady

0

Qui esempio guida codice come utilizzare urllib collegare tramite delega:

authinfo = urllib.request.HTTPBasicAuthHandler() 

proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"}) 

# build a new opener that adds authentication and caching FTP handlers 
opener = urllib.request.build_opener(proxy_support, authinfo, 
            urllib.request.CacheFTPHandler) 

# install it 
urllib.request.install_opener(opener) 

f = urllib.request.urlopen('http://www.google.com/') 
""" 
15

Python 3 è leggermente diverso. Si cercherà di rilevare automaticamente le impostazioni del proxy, ma se avete bisogno di impostazioni proxy specifiche o manuali, pensare a questo tipo di codice:

#!/usr/bin/env python3 
import urllib.request 

proxy_support = urllib.request.ProxyHandler({'http' : 'http://user:[email protected]:port', 
              'https': 'https://...'}) 
opener = urllib.request.build_opener(proxy_support) 
urllib.request.install_opener(opener) 

with urllib.request.urlopen(url) as response: 
    # ... implement things such as 'html = response.read()' 

Fare riferimento anche al the relevant section in the Python 3 docs

0

per HTTP e HTTPS utilizza:

proxies = {'http':'http://proxy-source-ip:proxy-port', 
      'https':'https://proxy-source-ip:proxy-port'} 

più deleghe possono essere aggiunti in modo simile

proxies = {'http':'http://proxy1-source-ip:proxy-port', 
      'http':'http://proxy2-source-ip:proxy-port' 
      ... 
      } 

utilizzo

filehandle = urllib.urlopen(external_url , proxies=proxies) 

Non utilizzare proxy (nel caso di collegamenti in rete)

filehandle = urllib.urlopen(external_url, proxies={}) 

usare un proxy di autenticazione tramite username e password

proxies = {'http':'http://username:[email protected]:proxy-port', 
      'https':'https://username:[email protected]:proxy-port'} 

Nota: evitare l'uso di caratteri speciali come :,@ in nome utente e password

Problemi correlati