requests基本用法

Requests is an elegant and simple HTTP library for Python, built for human beings.

requests素以简洁、友好著称,高度集成了python中urllib包并有很多人性化的方法可以使用,所以我们今天就来说一说requests。 就从基本用法开始

In [1]: import requests

In [2]: res = requests.get('http://www.baidu.com')

In [3]: res.status_code
Out[3]: 200

In [4]: res.reason
Out[4]: 'OK'

In [5]: type(res.text)
Out[5]: str

In [6]: res.text[:15]
Out[6]: '<!DOCTYPE html>'

In [7]: res.content[:15]
Out[7]: b'<!DOCTYPE html>'

In [8]: type(res.content)
Out[8]: bytes

In [9]: res.headers['content-type']
Out[9]: 'text/html'

In [10]: res.cookies
Out[10]: <RequestsCookieJar[Cookie(version=0, name='BDORZ', value='27315', port=None, port_specified=False, domain='.baidu.com', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=1532703485, discard=False, comment=None, comment_url=None, rest={}, rfc2109=False)]>
复制代码

以上方法都是requests常用的一些方法,content是以字节的方式访问请求响应体,对于纯文本信息text和content在解析上没有很大的差别,但是在非纯文本请求中python3会自动把请求到的数据以字节流的形式保存下来;还有一个res.json()方法一般是用于请求json数据的解析方法。

除了用requests外一般还会用到requests中的session长连接来请求。

In [12]: session = requests.session()

In [13]: session.get('http://www.baidu.com')
Out[13]: <Response [200]>
复制代码

session的方法基本和直接使用requests一样。

还有一些附带请求头和使用IP代理的方法

def get_html(url):
    proxy = {
        'http': '120.25.253.234:812',
        'https' '163.125.222.244:8123'
    }
    heads = {}
    heads['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0'
    req = requests.get(url, headers=heads,proxies=proxy)
    html = req.text
    return html
复制代码

转载于:https://juejin.im/post/5b59e7e76fb9a04f8f37aabb

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值