先安装requests库,通过 pip install requests 进行安装,也可以通过pycharm的python Interpreter直接搜索安装(详见文章url)
导入requests
import requests
3.目前我整理的常见用法总结,可以使用 http://httpbin.org/ 提供的接口请求来进行练习实践。这是具体的学习视频:Python HTTP 请求发送第三方模块 requests 使用
import requests
# 发送请求
r = requests.get("http://httpbin.org/#/HTTP_Methods/get_get")
print(dir(r)) # 响应对象的属性和方法
print(help(r)) # 获取帮助内容
print(r.url) # 获取响应URL
print(r.status_code) # 获取响应状态码
print(r.headers.get("content-type")) # 获取响应头 Content-Type字段
print(r.json()) # 获取响应JSON
print(r.text) # 获取响应主体内容
print(r.content) # 获取二进制响应内容
# 传递参数
payload = {"page": 1, "limit": 20}
r = requests.get("https://httpbin.org/get", payload)
print(r.text)
# 请求主体
payload = {"username": "curder", "password": "test"}
r = requests.post("http://httpbin.org/post", payload)
print(r.text)
# HTTP 身份验证
r = requests.get("https://httpbin.org/basic-auth/ml/dd", auth=("ml", "dd"))
print(r.text)
# 请求超时时间
try:
r = requests.get("http://httpbin.org/delay/3", timeout=2)
except requests.exceptions.ReadTimeout:
print('timeout')
# 也可以发送邮件或者通知
# 响应状态码的获取
r = requests.get("http://httpbin.org/status/422")
print(r.status_code)
# Cookies
r = requests.get("http://httpbin.org/cookies", cookies={"username": "123"})
print(r.text)
with requests.Session() as session:
jar = session.cookies
jar.set('test', 'value', domain="httpbin.org", path="/cookies")
r = requests.get("http://httpbin.org/cookies", cookies=jar)
print(r.text)
# 重定向
r = requests.get("http://httpbin.org/redirect_to", params={"url": "https://baidu.com"})
print(r.url, r.status_code, r.history, sep="\n")
# 请求上下文
with requests.Session() as session:
login_response = session.post('https://testerhome.com/account/sign_in', data={"login": "443", "password": "123"})
print(login_response.cookies)
r = session.get("https://testerhome.com/topics/waiting_audit_topics")
print(r.url)