import requests
import json
# 1、HTTP方法
requests.get('https://github.com/timeline.json') #GET请求
requests.post('http://httpbin.org/post') #POST请求
requests.put('http://httpbin.org/put') #PUT请求
requests.delete('http://httpbin.org/delete') #DELETE请求
requests.head('http://httpbin.org/get') #HEAD请求
requests.options('http://httpbin.org/get') #OPTIONS请求
# 2、Make a Request
url = 'http://www.baidu.com'
req = requests.get(url)
print(req.text)
# 3、response属性
import requests
response = requests.get('http://www.baidu.com/s', params={'wd': 'python'}) # GET参数实例
print(response.url)
print(response.text) #返回的内容,字符串形式
print(response.status_code) #返回码
print(response.content) #返回的内容,二进制形式
print(response.headers)
print(response.headers['content-type'])
print(response.headers.get('content-type'))
print(response.encoding)
print(response.json())
response.raise_for_status() #抛出异常 非200响应
# 4、get带参数
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('http://httpbin.org/get', params=payload)
print(r.url)
print(r.text)
# 5、数据流方式读取结果
r = requests.get('https://api.github.com/events', stream=True)
print(r.raw) #不解码
print(r.raw.read(10))
with open('output.txt', 'wb') as fd:
for chunk in r.iter_content(chunk_size=128): #解码
fd.write(chunk)
# 6、自定义头信息
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'} # 字符串,字节串,Unicode
r = requests.get(url, headers=headers)
# 7、post数据:字典
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)
# 8、post数据:列表
payload = (('key1', 'value1'), ('key1', 'value2'))
r = requests.post('http://httpbin.org/post', data=payload)
print(r.text)
# 9、post数据:字符串
url = 'http://httpbin.org/post'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))
print(r.text)
# 10、post数据:字符串
url = 'http://httpbin.org/post'
payload = {'some': 'data'}
r = requests.post(url, json=payload)
print(r.text)
# 11、上传多部分编码的文件
url = 'http://httpbin.org/post'
files = {'file': open('a.xls', 'rb')}
r = requests.post(url, files=files)
print(r.text)
# 12、上传多部分编码的文件
url = 'http://httpbin.org/post'
files = {'file': ('a.xls', open('a.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': ''})}
r = requests.post(url, files=files)
print(r.text)
# 13、字符串当文件发
url = 'http://httpbin.org/post'
files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
r = requests.post(url, files=files)
print(r.text)
# 14、cookies
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)
print(r.text)
# 15、cookies
jar = requests.cookies.RequestsCookieJar()
jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
url = 'http://httpbin.org/cookies'
r = requests.get(url, cookies=jar)
print(r.text)
# 16、timeout
requests.get('http://github.com', timeout=0.001)