Python之Requests

对于的新的环境可能没有安装requests库,可以子cmd窗口下进行requests库的安装,pip提供了在线安装的功能。
这里写图片描述
完成安装之后,通过一个简单的示例进入到下文中:

import requests

r = requests.get("http://www.baidu.com")
print r.status_code
r.encoding = 'utf-8'
print r.text

这里写图片描述

1、get()

这里写图片描述
而get的使用语法为:

requests.get(url,params=None,**kwargs)
url:拟获取的网页的url链接
params:url中的额外参数,字节或者字节流格式,可选
*kwargs:12个控制访问参数

打开get的源代码,发现实际上使用了request进行封装
这里写图片描述
对于上述示例中,如果状态码status_code 是 200,表示访问成功,而Response 对象的其它属性,如 类型和 头部,通过以下方式:

print type(r)
print r.headers

这里写图片描述
表示访问的是一个类。此外Response 还有以下诸多重要的属性
这里写图片描述
因此访问的流程如下:
这里写图片描述

print "the encoding way is :",r.encoding
print "the parent encoding is:",r.apparent_encoding
r.encoding = 'utf-8'
输出结果:
the encoding way is : ISO-8859-1
the parent encoding is: utf-8

这里写图片描述

爬取网页的通用代码框架:
由于网络连接有风险,因此异常处理就显得很重要了
这里写图片描述
对于response对象很重要的一点在于会判断返回码是否是200
这里写图片描述
现在来看看通用的代码框架是什么样的:

import requests

def getHTMLText(url):
    try:
        r = requests.get(url,timeout = 30)
        r.raise_for_status()#if the status is not 2000,HTTPError exception is thrown
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return #HTTPError exception

if __name__ == '__main__':
    url = "http://www.baidu.com"
    print getHTMLText(url)

http和request的对应的方法
这里写图片描述
这里写图片描述
这里写图片描述

猜你喜欢

转载自blog.csdn.net/rhx_qiuzhi/article/details/80189587
今日推荐