requests模块是Python中一个非常强大的模块,用于发送HTTP请求。
- 发送GET请求
import requests
response = requests.get('https://www.google.com/')
print(response.text)
- 发送POST请求
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post("https://httpbin.org/post", data=payload)
print(response.text)
- 添加headers
import requests
headers = {'User-Agent': 'my-app/0.0.1'}
response = requests.get('https://www.google.com/', headers=headers)
print(response.text)
- 添加cookies
import requests
cookies = {'cookies': 'value'}
response = requests.get('https://www.google.com/', cookies=cookies)
print(response.text)
- 使用timeout
import requests
response = requests.get('https://www.google.com/', timeout=1)
print(response.text)
- 使用proxies
import requests
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080',
}
response = requests.get('https://www.google.com/', proxies=proxies)
print(response.text)
- 使用auth
import requests
from requests.auth import HTTPBasicAuth
response = requests.get('https://www.google.com/', auth=HTTPBasicAuth('user', 'pass'))
print(response.text)
- 使用files
import requests
files = {'file': open('report.xls', 'rb')}
response = requests.post("https://httpbin.org/post", files=files)
print(response.text)
- 使用json
import requests
json = {'key': 'value'}
response = requests.post("https://httpbin.org/post", json=json)
print(response.text)
- 使用session
import requests
session = requests.Session()
session.auth = ('user', 'pass')
response = session.get('https://www.google.com/')
print(response.text)
- 使用response
import requests
response = requests.get('https://www.google.com/')
print(response.status_code) # 状态码
print(response.headers) # 头部信息
print(response.cookies) # cookies
print(response.url) # URL
print(response.history) # 历史记录
- 处理HTTPS证书
import requests
response = requests.get('https://www.google.com/', verify=False)
print(response.text)
- 处理超链接
import requests
response = requests.get('https://example.org/my_username/')
print(response.links['next']['url'])
- 使用hooks
import requests
def my