一.requests
**request.get()**方法可以得到一个请求相应对象,用response接收
# requests.get
import request
response = requests.get()
response作为响应对象有以下属性
-
respomse.content
返回二进制流数据
-
response.status_code
返回相应状态码
-
response.headers
返回相应头信息
-
response.url
查看请求地址(请求地址与真实返回的可能不一样)
-
response.cookies
返回浏览器带过来的cookie内容
-
response.history
是一个 response对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。
-
requests.post(url,data,headers)
# 请求方法用post
response = requests.post(url,data,headers)
# 做会话保持要在同同一组函数中先设置Session
import requests
headers ={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36"}
response = requests.get('http://www.baidu.com',headers=headers)
print(response.cookies)
for i,j in response.cookies.items():
print(i+"="+j)
import requests
from requests.packages import urllib3
# urllib3这个方法是用来消除警告认证的
urllib3.disable_warnings()
# verify参数是为了进行无阻拦的请求
response = requests.get("https://www.12306.cn",verify=False)
print(response.status_code)
import requests
proxies = {
'http':'socks4://127.0.0.1:9742',
'https':'socks4://127.0.0.1:9742'
}
response = requests.get("https://www.httpbin.org",proxies=proxies)
print(response.status_code)
import requests
from requests.exceptions import ReadTimeout
# timeout设置请求超时时间,可以捕获异常进行处理
try:
response = requests.get("https://www.httpbin.org/get",timeout=0.5)
print(response.status_code)
except ReadTimeout:
print('Timeout!')
import requests
from requests.auth import HTTPBasicAuth
r = requests.get("http://120.27.34.24:9001",auth=('user','123'))
print(r.status_code)