溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

解決python 3 urllib 沒有 urlencode 屬性的問題

發(fā)布時間:2020-08-19 21:16:17 來源:腳本之家 閱讀:203 作者:qq_38709565 欄目:開發(fā)技術(shù)

今天在pycharm(我用的python3)練習(xí)的時候,發(fā)現(xiàn)報了個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)容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI