AttributeError: module 'urllib' has no attribute 'parse'

参考链接:https://stackoverflow.com/questions/41501638/attributeerror-module-urllib-has-no-attribute-parse

首先贴出简单代码(代码的目的是将空格转为+):

import urllib

name = "abdada addfafaf asfasfaf"

s = urllib.parse.quote_plus(name)
print(s)

输出:

Traceback (most recent call last):
  File "G:/Python_Tensorflow/Test/test2.py", line 6, in <module>
    s = urllib.parse.quote_plus(name)
AttributeError: module 'urllib' has no attribute 'parse'

通过网上查资料,在stackoverflow.上找到一位大神的回答:

The urllib package serves as a namespace only. There are other modules under urllib like request and parse.
For optimization importing urllib doesn't import other modules under it. Because doing so would consume processor cycles and memory, but people may not need those other modules.
Individual modules under urllib must be imported separately depending on the needs.

Try these, the first one fails but the second succeeds because when flask is imported flask itself imports urllib.parse.

意思就是如果要用parse属性就必须加上import request或者加上flask

正确写法:

"方式1:"
# import requests
# import urllib

"方式2:"
from flask import Flask
import urllib


name = "abdada addfafaf asfasfaf"

s = urllib.parse.quote_plus(name)
print(s)

输出:

abdada+addfafaf+asfasfaf

猜你喜欢

转载自blog.csdn.net/oMoDao1/article/details/82873611