Ich versuche, Python zum Herunterladen des HTML-Quellcodes einer Website zu verwenden, erhalte jedoch diesen Fehler.
Traceback (most recent call last):
File "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\DICParser\src\WebDownload.py", line 3, in <module>
file = urllib.urlopen("http://www.python.org")
AttributeError: 'module' object has no attribute 'urlopen'
Ich folge der Anleitung hier: 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)
Ich benutze Python 3.
Dies funktioniert in Python 2.x.
Für Python 3 siehe docs :
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)
Eine Python 2 + 3 kompatible Lösung ist:
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)
import urllib.request as ur
s = ur.urlopen("http://www.google.com")
sl = s.read()
print(sl)
In Python v3 ist "urllib.request" ein eigenständiges Modul, daher kann "urllib" hier nicht verwendet werden.
Um ' dataX = rllib.urlopen (url) .read () ' in Python zum Laufen zu bringen (das wäre für Python richtig gewesen 2) Sie müssen nur 2 kleine Dinge ändern.
1: Die urllib-Anweisung selbst (fügen Sie die .request in der Mitte hinzu):
dataX = urllib.request.urlopen(url).read()
2: Die vorangehende import-Anweisung (von 'import urlib' zu:
import urllib.request
Und es sollte in python3 funktionieren:)
import urllib.request as ur
filehandler = ur.urlopen ('http://www.google.com')
for line in filehandler:
print(line.strip())
Lösung für Python3:
from urllib.request import urlopen
url = 'http://www.python.org'
file = urlopen(url)
html = file.read()
print(html)
Versuchen Sie für python 3 Folgendes:
import urllib.request
urllib.request.urlretrieve('http://crcv.ucf.edu/THUMOS14/UCF101/UCF101/v_YoYo_g19_c02.avi', "video_name.avi")
Das Video wird in das aktuelle Arbeitsverzeichnis heruntergeladen
Eine der möglichen Möglichkeiten:
import urllib
...
try:
# Python 2
from urllib2 import urlopen
except ImportError:
# Python 3
from urllib.request import urlopen
ihren Code, der in python2.x verwendet wird, können Sie folgendermaßen verwenden:
from urllib.request import urlopen
urlopen(url)
übrigens, schlagen Sie vor, dass ein anderes Modell mit dem Namen "Anfragen" benutzerfreundlicher ist. Sie können es mit pip install installieren und folgendermaßen verwenden:
import requests
requests.get(url)
requests.post(url)
Ich dachte, es ist einfach zu bedienen, ich bin auch Anfänger ... hahah