网络操作操作GET,POST
2019-12-22 本文已影响0人
wangyu2488
2019年12月15日
urllib库

一.urllib.request.urlopen
import urllib.request
with urllib.request.urlopen('http://www.sina.com.cn/') as response:
data = response.read()
html = data.decode()
print(html)

二.GET
结合 urllib.request.urlopen 一起使用
import urllib.request
import urllib.parse
url = 'http://www.51work6.com/service/mynotes/WebService.php'
email = '414875346@qq.com'
params_dict = {'email': email, 'type': 'JSON', 'action': 'query'}
params_str = urllib.parse.urlencode(params_dict)
print(params_str)
url = url + '?' + params_str # HTTP参数放到URL之后
print(url)
req = urllib.request.Request(url)
with urllib.request.urlopen(req) as response:
data = response.read()
json_data = data.decode()
print(json_data)

三.POST data=params_bytes
import urllib.parse
import urllib.request
url = 'http://www.51work6.com/service/mynotes/WebService.php'
# 准备HTTP参数
email = '414875346@qq.com'
params_dict = {'email': email, 'type': 'JSON', 'action': 'query'}
params_str = urllib.parse.urlencode(params_dict)
print(params_str)
params_bytes = params_str.encode() # 字符串转换为字节序列对象
req = urllib.request.Request(url, data=params_bytes) # 发送POST请求
with urllib.request.urlopen(req) as response:
data = response.read()
json_data = data.decode()
print(json_data)

四.Downloader例子
import urllib.request
url = 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png'
with urllib.request.urlopen(url) as response:
data = response.read()
f_name = 'download.png'
with open(f_name, 'wb') as f:
f.write(data)
print('下载文件成功')

如果您发现本文对你有所帮助,如果您认为其他人也可能受益,请把它分享出去。