【问题标题】:Import error: No module name urllib2导入错误:没有模块名称 urllib2
【发布时间】:2025-04-01 00:05:01
【问题描述】:

这是我的代码:

import urllib2.request

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

有什么帮助吗?

【问题讨论】:

  • 我看到您再次编辑了您的答案,所以我再次编辑了我的答案以回应:您当前的问题是您说的是urllib.urlopen("http://www.google.com/") 而不仅仅是urlopen("http://www.google.com/")

标签: python python-3.x urllib2


【解决方案1】:

而不是使用:

import urllib2

在python3中使用下面的代码

import urllib.request as urllib2

【讨论】:

    【解决方案2】:

    注意:urllib2 在 Python 3 中不再可用

    你可以试试下面的代码。

    import urllib.request 
    res = urllib.request.urlopen('url')
    output = res.read()
    print(output)
    

    您可以通过此link 了解有关urllib.request 的更多信息。

    使用 :urllib3

    import urllib3
    http = urllib3.PoolManager()
    r = http.request('GET', 'url')
    print(r.status)
    print( r.headers)
    print(r.data)
    

    另外,如果您想了解有关urllib3 的更多详细信息。关注这个link

    【讨论】:

      【解决方案3】:

      urllib2 documentation中所述:

      urllib2 模块已在 Python 3 中拆分为多个名为 urllib.requesturllib.error 的模块。在将源代码转换为 Python 3 时,2to3 工具会自动调整导入。

      所以你应该说

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

      您当前编辑的代码示例不正确,因为您说的是urllib.urlopen("http://www.google.com/") 而不仅仅是urlopen("http://www.google.com/")

      【讨论】:

      • 仍然出现错误,请参阅编辑。编辑:从 urllib.request 使用时仍然出现错误
      • @Sergio:这是urllib.request 而不是urllib2.request。 Python 2.x 中的 urlliburllib2 模块已合并到 Python 3 中的 urllib 模块中。
      • 这对我有用。谢谢伊莱。但是,当我尝试访问 URL 时出现超时错误。我也无法 ping google.com。看来我的网络正在使用代理。
      • 哇,向后兼容!
      【解决方案4】:

      最简单的解决方案:

      在 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)
      

      【讨论】:

        【解决方案5】:

        在python 3中,获取文本输出:

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

        【讨论】:

          【解决方案6】:

          在 Python 2 和 Python 3 中显示包内容的一些选项卡补全。

          在 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  
          

          在 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
          

          【讨论】:

            【解决方案7】:

            这在 python3 中对我有用:

            import urllib.request
            htmlfile = urllib.request.urlopen("http://google.com")
            htmltext = htmlfile.read()
            print(htmltext)
            

            【讨论】:

              【解决方案8】:

              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)
              

              虽然我已经在各自版本中测试了这两个代码。

              【讨论】:

              • 它的说法模块'urllib'没有属性'urlopen'
              • 我假设您正在使用 Py3.x 并再次检查 3.7.6 它有效。仔细检查您使用的是import urllib.request
              【解决方案9】:

              对于使用 Python 2(测试版本 2.7.3 和 2.6.8)和 Python 3(3.2.3 和 3.3.2+)的脚本,请尝试:

              #! /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())
              

              【讨论】:

                【解决方案10】:

                以上内容在 3.3 中对我不起作用。试试这个(YMMV 等)

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

                【讨论】: