使⽤用Requests库构建⼀一个HTTP请求

栏目: Python · 发布时间: 6年前

内容简介:User-Agent会告诉网站服务器,访问者是通过什么工具来请求的,如果是爬虫请求,一般会拒绝,如果是用户浏览器,就会应答。

https://developer.github.com/v3/migrations/users/

  • json.load() 将已编码的 JSON 字符串解码为 Python 对象
def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
    """Deserialize ``s`` (a ``str`` instance containing a JSON
    document) to a Python object.
复制代码
  • json.dumps() 将 Python 对象编码成 JSON 字符串
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
        allow_nan=True, cls=None, indent=None, separators=None,
        default=None, sort_keys=False, **kw):
    """Serialize ``obj`` to a JSON formatted ``str``.
复制代码
  • encode 将Python对象编码成JSON字符串
  • decode 将已编码的JSON字符串解码为Python对象
    使⽤用Requests库构建⼀一个HTTP请求
URL = 'https://api.github.com'

def build_uri(endpoint):
    return '/'.join([URL, endpoint])

def better_print(json_str):
    """Deserialize ``s`` (a ``str`` instance containing a JSON
        document) to a Python object."""
    return json.dumps(json.loads(json_str), indent=4)

def request_method():
    response = requests.get(build_uri('user/emails'), auth=('user', 'psw'))
    print(response.status_code)
    print(better_print(response.text))
>>[
  {
    "email": "octocat@github.com",
    "verified": true,
    "primary": true,
    "visibility": "public"
  }
]
复制代码

Github修改用户信息

Note: If your email is set to private and you send an email parameter as part of this request to update your profile, your privacy settings are still enforced: the email address will not be displayed on your public profile or via the API.
response = requests.patch(url, auth=('user', 'psw'), json={'name':'123'})

请求异常处理

request.get(url,timeout=timeout) #timeout=(x1,x2) 每步单独限制request-response时长 #timeout=x 总体限制request-response时长

from requests import exceptions
def timeout_request():
    try:
        response = requests.get(build_uri('user/emails'),timeout=10)
    except exceptions.Timeout as e:
        print(str(e))
    else:
        print(response.text)
复制代码

自定义Requests

使⽤用Requests库构建⼀一个HTTP请求
def hard_request():
    from requests import  Request, Session
    s = Session()
    headers = {'User-Agent': 'fake1.3.4'}
    req = Request('GET',build_uri('user/emails'), auth=('user','psw'),
                  headers = headers)
    prepped = req.prepare()
    print(prepped.body)
    print(prepped.headers)
    resp = s.send(prepped, timeout=5)
    print(resp.status_code)
    print(resp.headers)
    print(resp.text)
复制代码

关于User-Agent

User-Agent会告诉网站服务器,访问者是通过什么 工具 来请求的,如果是爬虫请求,一般会拒绝,如果是用户浏览器,就会应答。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

算法竞赛入门经典(第2版)

算法竞赛入门经典(第2版)

刘汝佳 / 清华大学出版社 / 2014-6-1 / CNY 49.80

《算法竞赛入门经典(第2版)》是一本算法竞赛的入门与提高教材,把C/C++语言、算法和解题有机地结合在一起,淡化理论,注重学习方法和实践技巧。全书内容分为12 章,包括程序设计入门、循环结构程序设计、数组和字符串、函数和递归、C++与STL入门、数据结构基础、暴力求解法、高效算法设计、动态规划初步、数学概念与方法、图论模型与算法、高级专题等内容,覆盖了算法竞赛入门和提高所需的主要知识点,并含有大量......一起来看看 《算法竞赛入门经典(第2版)》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试