requests库的安装

pip指令安装
pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple/

安装成功,测试
以访问百度为例
用status检测状态码:如果状态码是200,访问成功,否则访问失败

requests库的7个主要方法

requests.request


七种请求方法

13个参数








requests.get()

requests.head()

request.post()

requests.put()

requests.patch()

requests.delete()

get方法

访问一个网页的常用方法

response对象的属性



理解response的编码:

网页爬取有风险,异常处理


爬取网页的通用代码框架

import requests
def getHTMLText(url):
    try:
        r = requests.get(url, timeout = 30)
        r.raise_for_status()  #如果状态不是200,引发HTTPError异常
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return "产生异常"
if __name__ == "__main__":
    url = "http://www.baidu.com"
    print(getHTMLText(url))

HTTP协议



URL是通过HTTP协议存取资源的Internet路径,一个URL对应一个数据资源


HTTP协议与requests库的功能一一对应