解決python 3 urllib 沒有 urlencode 屬性的問題
今天在pycharm(我用的python3)練習(xí)的時候,發(fā)現(xiàn)報(bào)了個AttributeError: module 'urllib' has no attribute 'urlencode'的錯誤。后來發(fā)現(xiàn)python2和python3的urllib結(jié)構(gòu)不一樣。
下面我用pycharm中python3演示一下:
錯誤例子:
import urllib
import urllib.parse
wd = {"wd":"傳智播客"}
print(urllib.urlencode(wd))
結(jié)果:
C:\Users\DELL\AppData\Local\Programs\Python\Python36-32\python.exe E:/untitled/Python_Test/urllib2Demo1.py Traceback (most recent call last): File "E:/untitled/Python_Test/urllib2Demo1.py", line 5, in <module> print(urllib.urlencode(wd)) AttributeError: module 'urllib' has no attribute 'urlencode' Process finished with exit code 1
正確例子:
import urllib
import urllib.parse
wd = {"wd":"傳智播客"}
print(urllib.parse.urlencode(wd))
結(jié)果:
C:\Users\DELL\AppData\Local\Programs\Python\Python36-32\python.exe E:/untitled/Python_Test/urllib2Demo1.py wd=%E4%BC%A0%E6%99%BA%E6%92%AD%E5%AE%A2 Process finished with exit code 0
因此需要記住urllib庫在python2和python3之間是不同的。
普及一下知識點(diǎn):
urllib庫在python2與python3中的區(qū)別
Urllib是python提供的一個用于操作url的模塊。
在python2中,有urllib庫和urllib2庫。在python3中,urllib2合并到urllib庫中,我們爬取網(wǎng)頁的時候,經(jīng)常用到這個庫。
升級合并后,模塊中包的位置變化的地方較多。
以下是python2與python3中常用的關(guān)于urllib庫的變化:
在python2中使用import urllib2————對應(yīng)的,在python3中會使用import urllib.request,urllib.error
在python2中使用import urllib————對應(yīng)的,在python3中會使用import urllib.request,urllib.error,urllib.parse
在python2中使用import urlparse————對應(yīng)的,在python3中會使用import urllib.parse
在python2中使用urllib2.urlopen————對應(yīng)的,在python3中會使用urllib.request.urlopen
在python2中使用urllib.urlencode————對應(yīng)的,在python3中會使用urllib.parse.urlencode
在python2中使用urllib.quote————對應(yīng)的,在python3中會使用urllib.request.quote
在python2中使用cookielib.CookieJar————對應(yīng)的,在python3中會使用http.CookieJar
在python2中使用urllib2.Request————對應(yīng)的,在python3中會使用urllib.request.Request
以上就是urllib相關(guān)模塊從python2到python3的常見一些變化。
以上這篇解決python 3 urllib 沒有 urlencode 屬性的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python自帶緩存lru_cache用法及擴(kuò)展的使用
本篇博客將結(jié)合python官方文檔和源碼詳細(xì)講述lru_cache緩存方法是怎么實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
python django事務(wù)transaction源碼分析詳解
這篇文章主要介紹了python django事務(wù)transaction源碼分析詳解的相關(guān)資料,需要的朋友可以參考下2017-03-03
詳解python項(xiàng)目實(shí)戰(zhàn):模擬登陸CSDN
這篇文章主要介紹了python項(xiàng)目實(shí)戰(zhàn):模擬登陸CSDN,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
Python?Prim算法通過遍歷墻實(shí)現(xiàn)迷宮的生成
之前,我們在另外一篇文章中使用Prim算法生成了一個完美迷宮,利用的是遍歷網(wǎng)格的方法,這一次,我們要教教大家用遍歷墻的方法生成,感興趣的可以收藏一下2023-01-01

