我们都知道encode()函数用来进行编码,那么它和urlencode()有什么关系吗?
先看一个例程:
import urllib.request
import urllib.parse
data = {'name':'小明','age':'20',}
change0 = str(data).encode()
change1 = urllib.parse.urlencode(data)
change2 = urllib.parse.urlencode(data).encode()
print(change0)
print(change1)
print(change2)
我们对给出的字典类型data表单进行三种操作,结果如下:
可以看出encode()把字符串变成了字节类型,但它还是我们能看懂的形式。
而urlencode()把字典表单变成了我们看不懂的字符形式,其实它是变成url能识别的参数形式,如图是常见的含各种参数的url:
此时它还是字符串类型,通常在get方式时用作拼接包含参数的完整url
例程:
import urllib.parse
url = "http://www.nvren.com"
data = { "name":"cjh",
"age":"18",
"sex":"男"
}
q_string = urllib.parse.urlencode(data)
new_url = url + "?" + q_string
print(new_url)
输出:
看懂了这两个,那么urlencode().encode()就很好理解了,它把表单从字符串变成字节类型,通常用作post方式的表单提交,因为post 方法不允许进行url拼接的方式传递参数,必须把参数表单传给特定的data:
import urllib.request
import urllib.parse
init_url = "https://fanyi.baidu.com/sug"
word = input("input your word:")
#构建表单数据
form_data = { "kw":word,}
form_data = urllib.parse.urlencode(form_data).encode()
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) \
Chrome/63.0.3239.132 Safari/537.36X-Requested-With: XMLHttpRequest",}
try:
request = urllib.request.Request(init_url,headers)
response = urllib.request.urlopen(request,form_data)
temp_json = eval(response.read().decode())
tran_word = temp_json['data']
print("The word means:",tran_word[0]['v'])
except IndexError:
print("input error!please input again.....")
如图这是一个爬取百度翻译接口的程序,我们创建一个请求对象request,并在urlopen()时以参数形式传入处理过的form_data。