Importfehler: Kein Modulname urllib2


468

Hier ist mein Code:

import urllib2.request

response = urllib2.urlopen("http://www.google.com")
html = response.read()
print(html)

Irgendeine Hilfe?


4
Ich sehe, dass Sie Ihre Antwort erneut bearbeitet haben, also habe ich meine Antwort erneut bearbeitet, um zu antworten: Ihr aktuelles Problem ist, dass Sie sagen, urllib.urlopen("http://www.google.com/")anstatt nururlopen("http://www.google.com/")
Eli Courtwright

Antworten:


631

Wie in der urllib2Dokumentation angegeben :

Das urllib2Modul wurde in Python 3 auf mehrere Module mit dem Namen urllib.requestund aufgeteilt urllib.error. Das 2to3Tool passt Importe automatisch an, wenn Sie Ihre Quellen in Python 3 konvertieren.

Also solltest du stattdessen sagen

from urllib.request import urlopen
html = urlopen("http://www.google.com/").read()
print(html)

Ihr aktuelles, jetzt bearbeitetes Codebeispiel ist falsch, weil Sie urllib.urlopen("http://www.google.com/")statt nur sagen urlopen("http://www.google.com/").


1
Immer noch ein Fehler, siehe Bearbeiten. Bearbeiten: Immer noch ein Fehler bei der Verwendung von urllib.request

7
@ Sergio: Es ist urllib.requestund nicht urllib2.request. Die urllibund urllib2Module von Python 2.x wurden urllibin Python 3 zu dem Modul kombiniert .
Eli Courtwright

1
Das hat bei mir funktioniert. Danke Eli. Beim Versuch, auf eine URL zuzugreifen, wird jedoch eine Zeitüberschreitungsfehlermeldung angezeigt. Ich kann auch nicht google.com anpingen. Es scheint, dass mein Netzwerk Proxy verwendet.
Vaibhav

Woo, geh abwärtskompatibel!
user2589273

104

Für ein Skript, das mit Python 2 (getestete Versionen 2.7.3 und 2.6.8) und Python 3 (3.2.3 und 3.3.2+) funktioniert, versuchen Sie:

#! /usr/bin/env python

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

html = urlopen("http://www.google.com/")
print(html.read())

65

Das obige hat bei mir in 3.3 nicht funktioniert. Versuchen Sie dies stattdessen (YMMV usw.)

import urllib.request
url = "http://www.google.com/"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
print (response.read().decode('utf-8'))

24

Einige Tab-Vervollständigungen, um den Inhalt der Pakete in Python 2 und Python 3 anzuzeigen.

In Python 2:

In [1]: import urllib

In [2]: urllib.
urllib.ContentTooShortError      urllib.ftpwrapper                urllib.socket                    urllib.test1
urllib.FancyURLopener            urllib.getproxies                urllib.splitattr                 urllib.thishost
urllib.MAXFTPCACHE               urllib.getproxies_environment    urllib.splithost                 urllib.time
urllib.URLopener                 urllib.i                         urllib.splitnport                urllib.toBytes
urllib.addbase                   urllib.localhost                 urllib.splitpasswd               urllib.unquote
urllib.addclosehook              urllib.noheaders                 urllib.splitport                 urllib.unquote_plus
urllib.addinfo                   urllib.os                        urllib.splitquery                urllib.unwrap
urllib.addinfourl                urllib.pathname2url              urllib.splittag                  urllib.url2pathname
urllib.always_safe               urllib.proxy_bypass              urllib.splittype                 urllib.urlcleanup
urllib.base64                    urllib.proxy_bypass_environment  urllib.splituser                 urllib.urlencode
urllib.basejoin                  urllib.quote                     urllib.splitvalue                urllib.urlopen
urllib.c                         urllib.quote_plus                urllib.ssl                       urllib.urlretrieve
urllib.ftpcache                  urllib.re                        urllib.string                    
urllib.ftperrors                 urllib.reporthook                urllib.sys  

In Python 3:

In [2]: import urllib.
urllib.error        urllib.parse        urllib.request      urllib.response     urllib.robotparser

In [2]: import urllib.error.
urllib.error.ContentTooShortError  urllib.error.HTTPError             urllib.error.URLError

In [2]: import urllib.parse.
urllib.parse.parse_qs          urllib.parse.quote_plus        urllib.parse.urldefrag         urllib.parse.urlsplit
urllib.parse.parse_qsl         urllib.parse.unquote           urllib.parse.urlencode         urllib.parse.urlunparse
urllib.parse.quote             urllib.parse.unquote_plus      urllib.parse.urljoin           urllib.parse.urlunsplit
urllib.parse.quote_from_bytes  urllib.parse.unquote_to_bytes  urllib.parse.urlparse

In [2]: import urllib.request.
urllib.request.AbstractBasicAuthHandler         urllib.request.HTTPSHandler
urllib.request.AbstractDigestAuthHandler        urllib.request.OpenerDirector
urllib.request.BaseHandler                      urllib.request.ProxyBasicAuthHandler
urllib.request.CacheFTPHandler                  urllib.request.ProxyDigestAuthHandler
urllib.request.DataHandler                      urllib.request.ProxyHandler
urllib.request.FTPHandler                       urllib.request.Request
urllib.request.FancyURLopener                   urllib.request.URLopener
urllib.request.FileHandler                      urllib.request.UnknownHandler
urllib.request.HTTPBasicAuthHandler             urllib.request.build_opener
urllib.request.HTTPCookieProcessor              urllib.request.getproxies
urllib.request.HTTPDefaultErrorHandler          urllib.request.install_opener
urllib.request.HTTPDigestAuthHandler            urllib.request.pathname2url
urllib.request.HTTPErrorProcessor               urllib.request.url2pathname
urllib.request.HTTPHandler                      urllib.request.urlcleanup
urllib.request.HTTPPasswordMgr                  urllib.request.urlopen
urllib.request.HTTPPasswordMgrWithDefaultRealm  urllib.request.urlretrieve
urllib.request.HTTPRedirectHandler     


In [2]: import urllib.response.
urllib.response.addbase       urllib.response.addclosehook  urllib.response.addinfo       urllib.response.addinfourl

21

Python 3:

import urllib.request

wp = urllib.request.urlopen("http://google.com")
pw = wp.read()
print(pw)

Python 2:

import urllib
import sys

wp = urllib.urlopen("http://google.com")
for line in wp:
    sys.stdout.write(line)

Während ich beide Codes in jeweiligen Versionen getestet habe.


8

Einfachste aller Lösungen:

In Python 3.x:

import urllib.request
url = "https://api.github.com/users?since=100"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
data_content = response.read()
print(data_content)

6

In Python 3 erhalten Sie eine Textausgabe:

import io
import urllib.request

response = urllib.request.urlopen("http://google.com")
text = io.TextIOWrapper(response)

5

Das hat bei mir in python3 funktioniert:

import urllib.request
htmlfile = urllib.request.urlopen("http://google.com")
htmltext = htmlfile.read()
print(htmltext)
Durch die Nutzung unserer Website bestätigen Sie, dass Sie unsere Cookie-Richtlinie und Datenschutzrichtlinie gelesen und verstanden haben.
Licensed under cc by-sa 3.0 with attribution required.