举例urlopen中的data用法

data参数是可选的,如果要添加data,它要是字节流编码格式的内容,即bytes类型,
通过bytes()函数可以进行转化,另外如果你传递了这个data参数,它的请求方式就不再
是GET方式请求,而是POST

import urllib.parse
import urllib.request

data = {}
data['word'] = 'hello'

data = urllib.parse.urlencode(data).encode('utf-8')
response = urllib.request.urlopen('http://httpbin.org/post',data = data)
html = response.read()

print(html)

运行结果:
b'{\n "args": {}, \n "data": "", \n "files": {}, \n "form": {\n "word": "hello"\n }, \n "headers": {\n "Accept-Encoding": "identity", \n "Connection": "close", \n "Content-Length": "10", \n "Content-Type": "application/x-www-form-urlencoded", \n "Host": "httpbin.org", \n "User-Agent": "Python-urllib/3.6"\n }, \n "json": null, \n "origin": "115.198.140.140", \n "url": "http://httpbin.org/post"\n}\n'
代码很紊乱

你可能感兴趣的:(Python笔记,函数)