Python 3 urllib has no URLEncode attribute

Today, when practicing in pychar (I use python3), I found an attributeerror: module ‘urllib’ has no attribute ‘URLEncode’. Later, we found that the urllib structure of python2 and python3 is different.

Let me demonstrate it with python3 in pychar

Error example:

import urllib
import urllib.parse
wd =  {"wd":"video"}
print(urllib.urlencode(wd))

结果:

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

Right Example

import urllib
import urllib.parse
wd =  {"wd":"video"}
print(urllib.parse.urlencode(wd))

result:

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

So remember that the urllib library is different between python2 and python3.

Popularize the following knowledge points:

The difference of urllib library between python2 and python3

Urllib is a module provided by Python for operating URL.

In Python 2, there are urllib library and urllib2 library. In Python 3, urllib2 is merged into urllib library, which is often used when we crawl web pages.

After upgrading and merging, the location of packages in the module changes a lot.

Here are the common changes about urllib Library in python2 and python3:

    use import urllib2 in python2 — corresponding, import urllib2 will be used in python3 urllib.request , urllib.error Import urllib is used in python2 – Import urllib is used in python3 urllib.request , urllib.error , urllib.parse Use import urlparse in python2 — correspondingly, use import urlparse in python3 urllib.parse Use urllib2. Urlopen in python2 — corresponding, use urllib2. Urlopen in python3 urllib.request.urlopen Using in python2 urllib.urlencode ————Correspondingly, it will be used in Python 3 urllib.parse.urlencode Using in python2 urllib.quote ————Correspondingly, it will be used in Python 3 urllib.request.quote Using in python2 cookielib.Cookie Jar — corresponding, will be used in Python 3 http.CookieJar Use urllib2. Request in python2 — corresponding, use urllib2. Request in python3 urllib.request.Request

These are the common changes of urllib related modules from python2 to python3.

Read More: