2010-10-19 14 views
76

Sto provando a usare Python per scaricare il codice sorgente HTML di un sito Web ma sto ricevendo questo errore.AttributeError: l'oggetto 'module' non ha attributo 'urlopen'

Traceback (most recent call last):
File "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\DICParser\src\WebDownload.py", line 3, in file = urllib.urlopen(" http://www.python.org ") AttributeError: 'module' object has no attribute 'urlopen'

Sto seguendo la guida qui: http://www.boddie.org.uk/python/HTML.html

import urllib 

file = urllib.urlopen("http://www.python.org") 
s = file.read() 
f.close() 

#I'm guessing this would output the html source code? 
print(s) 

sto usando Python 3, grazie per l'aiuto!

risposta

120

Questo funziona in Python 2.x.

Per Python 3 un'occhiata qui:

http://docs.python.org/py3k/library/urllib.request.html?highlight=urllib#urllib.request.urlopen

import urllib.request 
with urllib.request.urlopen("http://www.python.org") as url: 
    s = url.read() 
#I'm guessing this would output the html source code? 
print(s) 
+1

Ciao Eumiro, usando l'istruzione 'with' in Python, suppongo che chiuda automaticamente la connessione una volta terminato l'utilizzo? Simile a una dichiarazione di utilizzo in C#? –

+0

@Sergio: esattamente! E attraverso il rientro vedi dove il tuo file è ancora aperto. – eumiro

+0

Grazie per l'aiuto –

10
import urllib.request as ur 
s = ur.urlopen("http://www.google.com") 
sl = s.read() 
print(sl) 

In Python v3 il "urllib.request" è un modulo di per sé, quindi, "urllib" non può essere utilizzato qui.

2
import urllib.request as ur 

filehandler = ur.urlopen ('http://www.google.com') 
for line in filehandler: 
    print(line.strip()) 
14

A + 3 soluzione compatibile Python 2 è:

import sys 

if sys.version_info[0] == 3: 
    from urllib.request import urlopen 
else: 
    # Not Python 3 - today, it is most likely to be Python 2 
    # But note that this might need an update when Python 4 
    # might be around one day 
    from urllib import urlopen 


# Your code where you can use urlopen 
with urlopen("http://www.python.org") as url: 
    s = url.read() 

print(s) 
1

Per ottenere risultati 'DATAX = urllib.urlopen (url) .read()' lavorare in python3 (questo sarebbe è stato corretto per python2) devi solo cambiare 2 piccole cose.

1: L'istruzione urllib stesso (aggiungere il .request al centro):

dataX = urllib.request.urlopen(url).read() 

2: L'istruzione import che lo precede (passaggio da 'importazione urlib' a:

import urllib.request 

E dovrebbe funzionare in python3 :)

Problemi correlati