AttributeError: 'module' object has no attribute 'request'

前端 未结 4 1549
灰色年华
灰色年华 2021-01-30 02:02

When I run the following code in Python 3.3:

import urllib
tempfile = urllib.request.urlopen(\"http://yahoo.com\")

I get the following error:

相关标签:
4条回答
  • 2021-01-30 02:30

    The urllib module has been split into parts and renamed in Python 3 to urllib.request, urllib.parse, and urllib.error.


    Import urllib.request instead of urllib.

    import urllib.request
    
    0 讨论(0)
  • 2021-01-30 02:44

    If this is on PyCharm, as was mine, make sure your file name isn't urllib.py.

    0 讨论(0)
  • 2021-01-30 02:49

    Interestingly, I noticed some IDE-depending behavior.

    Both Spyder and PyCharm use the same interpreter on my machine : in PyCharm I need to do

    import urllib.request

    while in Spyder,

    import urllib

    does fine

    0 讨论(0)
  • 2021-01-30 02:53
    • In visual code , u have to write import urllib.request instead of just import urllib.
    • Also, whenever errors such as module x has no attribute y occurs, it's because you have named the current file same as the package you are trying to import.
    • So, the way import in python works is that it first searches the current dir, and if it finds the module/package 'x' u were looking for , it assumes that it has found the target file, and searches for 'y'. And since u haven't defined 'y', the aforementioned error occurs.
    0 讨论(0)
提交回复
热议问题