当前位置:主页 > 软件编程 > Python代码 >

python 包 requests 实现请求操作

时间:2022-10-10 12:51:25 | 栏目:Python代码 | 点击:

一、安装

pip install requests

二、请求类型

import requests

requests.get('https://www.baidu.com')
requests.post('https://www.baidu.com')
requests.put('https://www.baidu.com')
requests.delete('https://www.baidu.com')
requests.head('https://www.baidu.com')
requests.options('https://www.baidu.com')

三、带参数请求

import requests

data = {
'name': 'autofelix',
'age': 25
}

response = requests.get('https://www.baidu.com', params=data)
print(response.url)
print(response.text)

四、自定义headers

import requests

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'
}
response =requests.get('https://www.baidu.com', headers=headers)
print(response.text)

五、请求属性

import requests

response = requests.get('https://www.baidu.com')

# 响应状态码
response.status_code
# 响应头
response.headers
# 响应cookie
response.cookies
# 请求url
response.url
# 历史记录
response.history

六、文件上传

import requests

files= {"files":open("git.jpeg","rb")}
response = requests.post('https://www.baidu.com/upload', files=files)

七、会话维持

import requests

s = requests.Session()
s.get('https://www.baidu.com/login')
response = s.get('https://www.baidu.com')

八、证书验证

import requests
from requests.packages import urllib3

urllib3.disable_warnings()
response = requests.get('https://www.12306.cn', verify=False)

九、代理设置

import requests

proxies= {
'http': 'http://127.0.0.1:9999',
'https': 'http://127.0.0.1:8888'
}
response = requests.get('https://www.baidu.com', proxies=proxies)

十、超时设置

import requests

requests.get('https://www.baidu.com', timeout=3)

十一、认证设置

import requests

response = requests.get('https://www.baidu.com', auth=('user', '123'))

十二、异常处理

import requests
from requests.exceptions import ReadTimeout,ConnectionError,RequestException

try:
response = requests.get('https://www.baidu.com', timout=0.1)
print(response.status_code)
except ReadTimeout:
print('timeout')
except ConnectionError:
print('connection Error')
except RequestException:
print('error')

您可能感兴趣的文章:

相关文章