• python requests库学习


    1.先bia一个国内镜像吧

      用法很简单 pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests

    2.大二的时候受到小甲鱼的蛊惑,拿urllib爬美女写真图。。。。。。真的是超级麻烦(其实也没多麻烦)

    3.前段时间听说有个很好用的包‘requests’,最近开学学计算机网络和互联网程序设计,于是就想起了这个,准备探索一下


     先大概看了一下,真的很方便,因为之前老遇到转码的问题。。。一窍不通。反正就是bytes()、decode()、encode(),之间互相试。。。。。。

    而这个真的就很简单了,拿到response以后直接.text就得到str了

     1 # -*- coding: utf-8 -*-
     2 import json
     3 import requests
     4 
     5 URL = 'https://api.github.com'
     6 
     7 def build_url(endpoint):
     8     return '/'.join([URL, endpoint])
     9 
    10 def better_print(json_str):
    11     return  json.dumps(json.loads(json_str), indent=4)
    12 
    13 def request_method():
    14     response = requests.get(build_url('users/liwenchi123000'))
    15     print(better_print(response.text))
    16 
    17 if __name__ == '__main__':
    18     request_method()

    这个就是用requests.get()方法,利用github的一个查看用户的api来得到一些用户信息,当时是保密的。

    带参数的请求,这个我自己还没有试,先看文档写下来吧

    普通的请求

    response = requests.get(URL, params={'param1':'value1','param2':'value2'})

    表单参数提交

    'Content-Type: application/x-www-form-urlencoded'
    response = requests.post(URL, data={'param1':'value1', 'param2':'value2'})

    json参数提交(github就是用的这种)

    'Content-Type: application/json'
    response = requests.post(URL, json={'param1': 'value1', 'param2': 'value2'})

    还有异常检测

    例如下面这个超时检测

     1 from requests import exceptions
     2 
     3 def timeout_request():
     4     try:
     5         response = requests.get('https://www.baidu.com/', timeout=0.05)
     6     except exceptions.Timeout as e:
     7         print(e)
     8     else:
     9         print(response.text)
    10 
    11 if __name__ == '__main__':
    12     timeout_request()

    0.05秒还是有点快的,显示的结果是

    HTTPSConnectionPool(host='www.baidu.com', port=443): Read timed out. (read timeout=0.05)

    如何自定义一个request

     1 def hard_request():
     2     from requests import Request, Session
     3     s = Session()
     4     headers = {'User-Agent':'fake1.3.4'}
     5     request = Request('GET', build_url('user/emails'), auth=('liwenchi123000','******'), headers=headers)
     6     prepared = request.prepare()
     7     # 先准备一个request但是不发出去,先看一下它的headers和body
     8     print(prepared.headers)
     9     print(prepared.body)
    10     # 现在发送,并设置延迟时间
    11     response = s.send(prepared, timeout=5)
    12     # 检查返回值
    13     print(response.status_code)
    14     print(response.request.headers)
    15     print(response.text)
    16 
    17 if __name__ == '__main__':
    18     hard_request()

    常见API

    response

    status_code 响应码

    reason 相应结果

    headers 头信息

    url 地址

    history 经历了什么

    elapsed

    request

    encoding 编码格式

    raw

    content

    text

    json

    实例展示

    用一个实例来练习一下

    比如我想爬取一个网站上的图片(这里我就用单一图片举例子了)

    download_image
    #download.py
    #coding: utf-8
    
    import requests
    from randomfilename import password
    
    def download_image(url):
        headers = {'User-Agent':'Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1'}
        #用字典伪造一个头
    response
    = requests.get(url, headers = headers) with open(password(6) + '.jpg', 'wb') as f:
    #随机生成一个6位的文件名 f.write(response.content)
    print(response.reason) download_image('http://img1.gamersky.com/image2017/09/20170909_zl_91_7/gamersky_06origin_11_2017991730925.jpg')
    #randomfilename.py
    import random
    import string
    
    '''
        2017年09月19日
        随机生成字符串
    '''
    
    def password(len): filename = '' for i in range(0, len): filename += random.choice(string.ascii_lowercase) return filename

    这里我想说response.text和response.content在不同的语境下获得的值是不同的,这个我目前还没试过,所以在写入文件之前可以先打印一下试试看

  • 相关阅读:
    22.112.leetcode_path_sum
    21.leetcode111_minimum_depth_of_binary_tree
    20.leetcode110_balanced_binary_tree
    19.leetcode108_convert_sorted_array_to_binary_search_tree
    论文阅读 | RoBERTa: A Robustly Optimized BERT Pretraining Approach
    CheckList:ACL 2020 Best Paper
    激活函数综述
    盘点深度学习中的损失函数
    逻辑回归
    机器学习之参数估计
  • 原文地址:https://www.cnblogs.com/liwenchi/p/7455209.html
Copyright © 2020-2023  润新知