zoukankan      html  css  js  c++  java
  • 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')])")))

  • 相关阅读:
    mysql max_allowed_packet过小导致的prepare失败
    linux tcp/ip编程和windows tcp/ip编程差别以及windows socket编程详解
    mysql metadata lock锁
    velocity merge作为工具类从web上下文和jar加载模板的两种常见情形
    mysql 5.7.15发布
    mysql 5.6.33发布
    2016年09月编程语言排行榜
    postgresql 9.6 rc1发布
    www.97top10.com--做最好的技术交流网站
    nginx/ajax跨子域请求的两种现代方法以及403解决
  • 原文地址:https://www.cnblogs.com/kristin/p/10343178.html
Copyright © 2011-2022 走看看