关于python:在Python3.6中安装urllib

installing urllib in Python3.6

我想导入urllib以使用功能"请求"。 但是,尝试这样做时遇到错误。 我尝试了pip install urllib,但仍然遇到相同的错误。 我正在使用Python 3.6。 真的感谢任何帮助。

我确实使用以下代码导入urllib.request:

1
2
3
4
5
6
7
8
import urllib.request, urllib.parse, urllib.error
fhand = urllib.request.urlopen('data.pr4e.org/romeo.txt')
counts = dict()
for line in fhand:
    words = line.decode().split()
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)

但是它给了我这个错误:ModuleNotFoundError:没有名为" urllib.parse"的模块; 'urllib'不是软件包

这是错误的屏幕截图


urllib是一个标准库,您无需安装。 import urllib


更正的代码是

1
2
3
4
5
6
7
8
import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
counts = dict()
for line in fhand:
    words = line.decode().split()
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)

运行上面的代码会产生

1
{'Who': 1, 'is': 1, 'already': 1, 'sick': 1, 'and': 1, 'pale': 1, 'with': 1, 'grief': 1}


urllib是标准的python库(内置),因此您无需安装它。 如果需要使用request,只需导入它即可:

1
import urllib.request

如果它不起作用,则可能是您以错误的方式编译了python,请客气并提供更多详细信息。


发生这种情况是因为名为urllib.py的本地模块遮盖了您尝试使用的已安装请求模块。 当前目录位于sys.path之前,因此本地名称优先于已安装名称。

出现这种情况时,另一个调试技巧是仔细查看Traceback,并意识到所涉及脚本的名称与您要导入的模块匹配。

将文件重命名为其他名称,例如url.py
然后,它工作正常。
希望能帮助到你!