post请求一般用于表单提交,把参数内容以bytes类型传入
注意,参数需要进行url转码!
import json
import pprint
from urllib import request, parse
def fetch_page():
username = 'xxxxxxxxx'
password = 'yyyyyyyyy'
#参数需要进行url转码
post_data = parse.urlencode([
('username', username),
('password', password),
])
#构造Request对象
http_request = request.Request('http://httpbin.org/post')
http_request.add_header('Refer', 'yyyyyyyyy')
http_request.data = post_data.encode('utf-8')
with request.urlopen(http_request) as http_response:
content = http_response.read()
result = json.loads(content.decode('utf-8'))
pprint.pprint(result)
def main():
fetch_page()
if __name__ == '__main__':
main()
post请求只需构建一个Request对象,并把参数传递给Request对象的data属性即可(也可以在urlopen方法中传递给data参数)。
下面讲到url编码转换的问题
from urllib import parse
username = 'hhhhhhhh'
password = 'fhsfgu@#$%^&*'
post_data = parse.urlencode([
('username', username),
('password', password),
])
print(post_data)
执行结果
username=hhhhhhhh&password=fhsfgu%40%23%24%25%5E%26%2A
从执行结果中,我们可以看到,urlencode函数会合并参数成一个字符串,并且还会把特殊字符转换为url统一的编码格式。