2010-10-19 13 views
76

Estoy tratando de usar Python para descargar el código fuente HTML de un sitio web, pero recibo este error.AttributeError: el objeto 'module' no tiene ningún atributo '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'

estoy siguiendo la guía aquí: 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) 

estoy usando Python 3, gracias por la ayuda!

Respuesta

120

Esto funciona en Python 2.x.

Para Python 3 vistazo aquí:

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

Hola Eumiro, usando la instrucción 'with' en Python, supongo que cierra la conexión automáticamente una vez que ha terminado de usarla. ¿Similar a una declaración de uso en C#? –

+0

@Sergio: ¡exactamente! Y a través de la sangría, verá dónde todavía se abre el archivo. – eumiro

+0

Gracias por la ayuda –

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

En Python v3 el "urllib.request" es un módulo por sí mismo, por lo tanto, "urllib" no se pueden utilizar aquí.

2
import urllib.request as ur 

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

una pitón 2 + 3 es solución compatible:

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

Para obtener 'DATAX = urllib.urlopen .read (url)()' trabajando en python3 (esto han sido correctos para python2) solo debes cambiar 2 pequeñas cosas.

1: La declaración urllib sí mismo (añadir el .request en el medio):

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

2: La declaración de importación que lo precede (cambio de 'importación urlib' a:

import urllib.request 

Y debería funcionar en python3 :)

Cuestiones relacionadas