嵩天教授的Python网络爬虫与信息提取课程笔记——requests库入门

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/JohnyHe/article/details/82831977

本文目录

  1. Requests库介绍
  2. `requests库的7个主要方法介绍
  3. Response类属性简介
  4. Reponse类中的encodingapparent_encoding对比
  5. Requests库异常简介
    ———————————————————————————————————————
1. Requests库介绍
  • requests库是一个优秀的第三方请求库,当然python自带的标准库urllib库下的request模块的相关方法也可以进行网页请求。
  • 本人常用的两种网页请求技术路线:1). requests库下的get(), post()方法;2).urllib.request.urlopen()方法
2. `requests7个主要方法介绍
方法 说明
requests.request() 构造一个Request请求,作为以下方法的基础调用方法
requests.get() 获取网页的主要方法,对应于HTTP的GET
requests.head() 获取网页的请求头,对应于HTTP的HEAD
requests.post() 向HTML页面提交POST请求,对应于HTTP的POST
requests.put() 向HTML页面提交PUT请求,对应于HTTP的PUT
requests.delete 向HTML页面提交DELETE请求,对应于HTTP的DELETE
requests.patch() 向HTML页面提交局部修改请求,对应于HTTP的PATCH

在这7个方法中,我们重点介绍requests.get()requests.head()两个方法,这两个方法是我们最常用的方法。

  • requests.get():该方法用于获取网页内容
  • requests.head():当请求的资源较大时,可以通过获取请求头信息查看相关内容
  • 直接贴源码进行分析:
def get(url, params=None, **kwargs):
    r"""Sends a GET request.

    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    kwargs.setdefault('allow_redirects', True)
    return request('get', url, params=params, **kwargs)

通过源码可知,原来requests.get()方法调用了requests.request(method, url, **kwargs)方法创建一个Request对象向服务器发送get请求,返回一个Response对象。ok,可想而知,其他方法如requests.head()方法内部的调用与requests.get()类似,在此不一一介绍了。

3. ResponseRequest对象简介
1). Response

此处仅介绍嵩天老师说的几个属性,主要有status_code,encoding,apparent_encoding,content,text

在此之前,先简单介绍一下python的内置装饰器@property的知识: 简单说,@property的作用就是将一个getter()方法变成一个属性调用。而以上有一些属性就是通过@property注解对应的方法后得以通过属性形式进行调用的。

以下是Response类的属性: 以下均可从requests.Response的源码中查看

__attrs__ = [
        '_content', 'status_code', 'headers', 'url', 'history',
        'encoding', 'reason', 'cookies', 'elapsed', 'request'
    ]

可以看出,像apparent_encodingcontenttext皆是由@property注解对应方法后得以通过属性形式调用的。

  1. status_code:HTTP请求的返回状态码,常用的如200(成功),404(资源不存在),403(禁止访问),500(服务器错误)等等。
  2. encoding:从HTTP header中的charset取出的编码
  3. apparent_encoding:从实际返回的网页内容中分析出来的编码。它是由@property注解apparent_encoding()方法从而作为属性调用。源码如下:
@property
    def apparent_encoding(self):
        """The apparent encoding, provided by the chardet library."""
        return chardet.detect(self.content)['encoding']
  1. text:以unicode编码方式返回资源,下面贴出源码的方法注释:
@property
    def text(self):
        """Content of the response, in unicode."""
  1. content:以二进制编码方式返回资源,下面贴出源码的方法注释:
 @property
    def content(self):
        """Content of the response, in bytes."""
4. Response类中encodingapparent_encoding的对比

前面提到过,encoding指的是从HTTP header中的charset取得的编码,apparent_encoding是从实际的请求资源内容中分析出来的编码。故二者可能存在不一致的情况,此时可以将apparent_encoding的值赋给encoding,从而获取正常的网页内容。示例如下:

  • 以百度首页为例,运行一下代码
import requests

url = "http://www.baidu.com"
response = requests.get(url)
print(response.encoding)            # 输出结果:ISO-8859-1
print(response.apparent_encoding)   # 输出结果:utf-8

从上面代码可以看出,encodingapparent_encoding返回的结果并不相同。因此,如果要使网页内容正常显示,只需要添加代码response.encoding = response.apparent_encoding即可。

5. Requests库的异常简介
异常 说明
requests.ConnectionError 网络连接错误异常,如DNS查询失败、拒绝连接等
requests.HTTPError HTTP HTTP错误异常
requests.URLRequired URL缺失异常
requests.TooManyRedirects 超过最大重定向次数,产生重定向异常
requests.ConnectTimeout 连接远程服务器异常
requests.Timeout 请求URL超市,产生超时异常

需要注意的是,requests.ConnectTimeoutrequests.Timeout的区别在于前者仅仅是连接远程服务器时产生的超时异常,后者是指整个请求过程超时的产生的异常。
此外,老师在课堂中提到一个简单的通用代码框架,如下:

import requests

def getHTMLText(url):
	try:
		response = requests.get(url, timeout=30)
		r.raise_for_status()		# 若状态码不是200,则抛出HTTPError异常
		reponse.encoding = response.apparent_encoding
		return response.text
	except:
		return "产生异常"
	
if __name__ == "main":
	url = "http://www.baidu.com"
	print(getHTMLText(url))

此处需要注意一个新知识:response.raise_for_status(),该方法用于检查服务器返回的状态码,如果不是200(或者2xx)则会抛出HTTPError异常

猜你喜欢

转载自blog.csdn.net/JohnyHe/article/details/82831977