• python实现http get请求


    • 接口请求方式为get请求,如下图抓包查看

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

    • 使用到的函数

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

  • 相关阅读:
    iOS UI调试神器,插件injection for Xcode使用方法
    iOS 开发笔记-Objective-C之KVC、KVO
    iOS 测试企业应用的分发
    iOS 阅读唐巧博客心得
    iOS 添加启动图片
    Xcode 常用命令
    iOS 开发笔记
    iOS 开发常用链接总结
    iOS
    iOS UI基础
  • 原文地址:https://www.cnblogs.com/kristin/p/10343178.html
Copyright © 2020-2023  润新知