2010-10-19 11 views
76

J'essaie d'utiliser Python pour télécharger le code source HTML d'un site Web, mais je reçois cette erreur.AttributeError: l'objet 'module' n'a pas d'attribut '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'

que je suis le guide ici: 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) 

J'utilise Python 3, merci pour l'aide!

Répondre

120

Cela fonctionne dans Python 2.x.

Pour Python 3 regarder ici:

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

Salut Eumiro, en utilisant l'instruction 'with' en Python Je suppose qu'il ferme la connexion automatiquement une fois qu'il est fait de l'utiliser? Semblable à une déclaration d'utilisation en C#? –

+0

@Sergio: exactement! Et à travers l'indentation, vous voyez où votre fichier est encore ouvert. – eumiro

+0

Merci pour l'aide –

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

En Python v3 le "urllib.request" est un module par lui-même, donc "urllib" ne peut être utilisé ici.

2
import urllib.request as ur 

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

Une solution compatible Python 2 + 3 est la suivante:

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

Pour obtenir 'Datax = urllib.urlopen (url) .Lire()' travaillant dans python3 (ce qui ont été corrects pour python2) vous devez juste changer 2 petites choses.

1: L'instruction urllib lui-même (ajouter le .request au milieu):

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

2: L'instruction d'importation qui le précède (passage de 'urlib d'importation' à:

import urllib.request 

Et il devrait fonctionner dans python3 :)