1. 程式人生 > >AttributeError: module 'urllib' has no attribute 'parse'

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