import requests
python中的数据请求(http请求),是第三方库requests来提供的
1.requests第三方库的使用
get/post方法都是发送请求获取接口提供的数据
a.
get(url, params=None)
url - 字符串,需要获取的数据的接口地址
params - 字典,参数列表(给服务器发送请求的时候需要传给服务器的数据)
https://www.apiopen.top/meituApi?page=1
完整的接口: 协议://主机地址/路径?参数名1=值1&参数名2=值2
b.post(url, params=None, json=None)(暂时不管!)
response = requests.get('http://rap2api.taobao.org/app/mock/121184/studentsInfo')
print(response.json())
def main():
# 1.发送请求,并且获取返回的数据
# 服务返回的数据叫响应
response = requests.get('https://www.apiopen.top/meituApi?page=1')
# response = requests.get('https://www.apiopen.top/meituApi', {'page': 1})
print(response)
# 2.从响应中获取数据
# a.获取json数据
content_json = response.json() # 会自动将json数据转换成python对应的数据
print(type(content_json))
print(content_json)
# b.获取字符串数据
content_text = response.text
print(type(content_text))
print(content_text)
# c.获取二进制数据(原始数据)
content_bytes = response.content
print(content_bytes)
# 下载图片
response2 = requests.get('http://tx.haiqq.com/uploads/allimg/170506/0H92Q915-1.jpg')
with open('luffy.jpg', 'wb') as f:
f.write(response2.content)