1.发送GET请求
1.1不携带url参数的GET请求
#导入requests库
import requests
#准备
url base_url = 'https://www.baidu.com/'
#发送GET请求,接收服务器返回的相应信息
response = requests.get(url = base_url)
#查看响应码
print(response.status_code)
1.2携带url参数的GET请求
#方式一
import requests
base_url = 'https://www.baidu.com/s'
param = 'wd=python'
full_url = base_url + '?' + param
response = requests.get(full_url)
print(response.status_code)
#方式二
import requests
base_url = 'https://www.baidu.com/s'
wd_params = {'wd':'python'}
response = requests.get(base_url,params=wd_params)
print(response.status_code)
2.发送POST请求
import requests
base_url = 'http://mp-meiduo-python.itheima.net/login/'
# 准备请求数据
form_data = {
'csrfmiddlewaretoken':'FDb8DNVnlcFGsjIONtwiQoi6PtmCLeBsRgyjx2o2nsZ4MXDEGDeM2dUImEkj9O7t',
'username': 'admin',
'pwd': 'admin',
'remembered': 'on'}
response = requests.post(base_url, data=form_data) # 根据URL构造请求,发送POST请求
print(response.status_code) # 查看响应信息的状态码
3.定制请求头
import requests
#base_url = 'https://www.zhihu.com/signin'
base_url = 'https://www.tianqi.com/'
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64'
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'}
# 根据URL和请求头构造请求,发送GET请求,接收服务器返回的响应
response = requests.get(base_url, headers=header)
response.encoding = 'utf-8'
# 查看响应内容
print(response.text)