python爬虫:requests库的基本方法函数及运用框架

安装:

 Win 平台:“以管理员身份运行” cmd,执行   pip install requests

小测:

>>>import requests

>>>r=requests.get("http://www.baidu.com")

>>>print(r.status_code)

200

>>>r.text

Requests库的7个主要方法:

 

requests.requests()为基础方法

request.requests(method, url, **kwargs)


method包含上述的get/put/post/options 等七种方法

url   为获取页面的链接
**kwargs 为控制访问的参数,共13个,可自主按需选择


params :    字典或字节序列,可以作为 参数 加入到url中
data :          对象,作为request的对应内容
json:           JSON格式的数据,作为Request的内容
headers :   字典,http定制的头 字段
cookies :   request中的cookie
files :         字典,向链接传输文件
auth :         元组,认证http功能
timeout :   设定超时时间,秒为单位
proxies :  字典类型,可以设定访问的代理服务器
allow_redirects :开关,允许不允许重定向
stream :   文件下不下载,默认下载
verify :  认证ssl
cert :   本地ssl路径


Response对象的属性:

 理解Requests库的异常:

爬去网页的通用代码框架:

import requests
def getHTMLText(url):
      try:
            r=requests.get(url,timeout=30)
            r.raise_for_status()  #如果状态不是200,引发HTMLError异常
            r.encoding=r.apparent_encoding
            return r.text
       except:
             return "产生异常"

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

HTTP协议:

HTTP,Hypertext Transfer Protocol,超文本传输协议
HTTP是一个基于“请求与响应”模式的、无状态的应用层协议 HTTP协议采用URL作为定位网络资源的标识,URL格式如下:
http : //host[:port][path]


host: 合法的Internet主机域名或IP地址 port: 端口号,缺省端口为80 path: 请求资源的路径
HTTP
HTTP,Hypertext Transfer Protocol,超文本传输协议
HTTP URL实例:
http://www.bit.edu.cn http://220.181.111.188/duty
HTTP URL的理解:
URL是通过HTTP协议存取资源的Internet路径,一个URL对应一个数据资源

HTTP协议对资源的操作:

HTTP协议与Requests库:

原文地址:https://www.cnblogs.com/Romantic-Chopin/p/12451040.html