标签:not like color delete response post .text switch load
实例引入
import requests res = requests.get(‘https://www.baidu.com‘) print(type(res)) print(res.status_code) print(type(res.text) print(res.text) print(res.cookies)
各种请求方法
import requests requests.post(‘http://httpbin.org/post‘) requests.put(‘http://httpbin.org/put‘) requests.delete(‘http://httpbin.org/delete‘) requests.head(‘http://httpbin.org/get‘) requests.options(‘http://httpbin.org/get‘)
请求
基本GET请求
基本写法
import requests res = requests.get(‘http://httpbin.org/get‘) print(res.text)
带参数GET请求
import requests response = requests.get("http://httpbin/get?name=germey&age22") print(response.text) import requtests data = { ‘name‘ : ‘gemey‘, ‘age‘ : 22 } response = requests.get(‘http://httpbin.org/get‘, params=data) print(response.text)
解析json
import requests import json response = requests.get("http://httpbin.org/get") print(type(response.text)) print(response.json()) print(json.loads(response.text)) //这个和上面那个打印方式是一样 print(type(response.json()))
获取二进制数据
import requests response = requests.get(‘https://github.com/favicon.ico") print(type(response.text), type(response.content)) print(response.text) print((response.content) with open(‘favicon.ico‘, ‘wb‘) as f: f.write(response.content) f.close()
添加headers
import requests response = requests.get(‘https://www.zhihu.com/explore‘) print(response.text)
import requests headers = { ‘User-Agent‘:‘ Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36‘ } response = requests.get("https://www.zhihu.com/explore", headers = headers) print(response.text)
基本POST请求
import requests date ={‘name‘: ‘germey‘, ‘age‘: 22} response =requests.post("http://httpbin.org/post", data = data) print(response.text)
import requests data = {‘name‘: ‘gemey‘, ‘age‘: 22} headers = { ‘User-Agent‘:‘ Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36‘ } response = requests.post("https://httpbin.org/post",data = data, headers = headers) print(response.json())
响应
reponse属性
import requests response = requests.get"http://www.jianshu.com") print(type(response.status.code), response.status_code) print(type(response.headers), response.headers) print(type(response.cookies), response.cookies) print(type(response.url), response.url) print(type(response.history), response.history)
状态码判断
import requests response = requests.get(‘http://www.jianshu.com‘) exit() if not response.status_code == requests.codes.ok else print(‘Request Successfully‘) response = requests.get(‘http://www.jianshu.com‘) exit() if not response.status_code == 200 else print(‘Request Successfully‘) 100: (‘continue‘,), 101: (‘switching_protocols‘,), ....
标签:not like color delete response post .text switch load
原文地址:http://www.cnblogs.com/ecwork/p/7398699.html