python实现http get请求

时间:2021-11-21 12:35:31
  • 接口请求方式为get请求,如下图抓包查看

python实现http get请求

  • Python实现脚本请求接口并以中文打印接口返回的数据
 import urllib.parse
import urllib.request url = "https://..../manage/region/list" # 定义请求数据,并且对数据进行赋值
values={}
values['status']= 'hq'
values['token']= 'C6AD7DAA24BAA29AE14465DDC0E48ED9' # 对请求数据进行编码
data = urllib.parse.urlencode(values).encode('utf-8')
print(type(data)) # 打印<class 'bytes'>
print(data) # 打印b'status=hq&token=C6AD7DAA24BAA29AE14465DDC0E48ED9' # 若为post请求以下方式会报错TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.
# Post的数据必须是bytes或者iterable of bytes,不能是str,如果是str需要进行encode()编码
data = urllib.parse.urlencode(values)
print(type(data)) # 打印<class 'str'>
print(data) # 打印status=hq&token=C6AD7DAA24BAA29AE14465DDC0E48ED9 # 将数据与url进行拼接
req = url + '?' + data
# 打开请求,获取对象
response = urllib.request.urlopen(req)
print(type(response)) # 打印<class 'http.client.HTTPResponse'>
# 打印Http状态码
print(response.status) # 打印200
# 读取服务器返回的数据,对HTTPResponse类型数据进行读取操作
the_page = response.read()
# 中文编码格式打印数据
print(the_page.decode("unicode_escape"))
  • 执行脚本,接口返回数据

python实现http get请求

  • 使用到的函数

urllib.parse.urlencode() 把key-value这样的键值对转换成a=1&b=2这样的字符串

urllib.request.urlopen() 打开指定的url,就是进行get请求

response.read() 读取HTTPResponse类型数据

  • 脚本执行过程报错记录,requests爬虫时开启代理会报以下错误

requests.exceptions.SSLError: HTTPSConnectionPool(host='api.****.cn', port=443):Max retries exceeded with url: //manage/region/list (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))