Requests(2):模拟发送GET请求
模拟发送GET请求
前置条件:导入requests库
一、发送不带参数的get请求
代码如下:
以百度首页为例
import requests # 发送get请求 response = requests.get(url="http://www.baidu.com") print(response.content.decode("utf-8")) # 以utf-8的编码输出内容
二、发送带参数的get请求
发送带参数的get请求有几种方式
方式一:参数在URL中
代码如下:
以百度首页为例
import requests # 发送带参数的get请求 # 方式一:参数在URL中 # http 协议,www.baidu.com 主机号,/s 请求地址,wd=猫 参数 host = "http://www.baidu.com/s?wd=猫" # 因为百度服务器会对头部信息做检查所以需要添加请求头 headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36'} response = requests.get(url=host,headers=headers) print(response.content.decode("utf-8"))
方式二:参数在字典中
代码如下:
以百度首页为例
import requests # 方式二:参数在字典中 host = "http://www.baidu.com/s" headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36'} data = {'wd':'金钱豹'} # 参数在字典中 response = requests.get(url=host,headers=headers,params=data) print(response.content.decode('utf-8'))
获取响应数据的基本信息
代码如下:
以百度首页为例
import requests # 发送get请求 response = requests.get(url="http://www.baidu.com") # 获取响应的基本信息 print( "状态码:", response.status_code ) print( "请求URL:",response.url ) print( "头部信息:", response.headers ) print( "cookie信息:", response.cookies ) print("字节形式信息:",response.content ) print("文本信息:",response.text) print("编码格式:",response.encoding)
以百度首页为例