python 包 requests 实现请求操作

一、安装

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')

八、证书验证

  • verify设置False关闭证书验证
  • urllib3可以解决InsecureRequestWarning提示
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'))

十二、异常处理

  • ReadTimeout是超时错误
  • ConnectionError是网络错误
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')

到此这篇关于python 包 requests 实现请求操作的文章就介绍到这了,更多相关python  equests 请求操作内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(python 包 requests 实现请求操作)