Python crawler learning (1) Introduction to the Requests library

(1) Getting started with the Requests library

(1) HTTP protocol

#HTTP 超文本传输协议
#HTTP是一种基于“请求与响应”模式的、无状态的应用层协议
#HTTP采用URL作为定位网络资源的标识,一个URL对应一个数据资源
-------------------------------
http://host[:post][path]
host:合法的Internet主机域名或IP地址
port:端口号,缺省为80
path:请求资源的路径
-------------------------------
method effect
GET Request resource for URL location
HEAD Request message report (header information) for obtaining URL location resources
POST Request to append new data to the resource at the URL
PUT Request to store a resource to the URL location, overwriting the resource at the original URL location (update full coverage)
PATCH Request to partially update the resource of the URL location, that is, change part of the content of the resource there (partial coverage update)
DELETE Request to delete the resource stored in the URL location

(2) The 7 main methods of the Requests library

method effect
requests.request(method, url, **kwargs) Construct a request to support the basic methods of the following methods
requests.get() The main method of obtaining HTML web pages, corresponding to HTTP GET
requests.head() Method for obtaining HTML web header information, corresponding to HTTP HEAD
requests.post() The method of submitting a POST request to an HTML webpage, corresponding to HTTP POST
requests.put() Method for submitting PUT request to HTML webpage, corresponding to HTTP PUT
requests.patch() Submit a partial modification request to an HTTP webpage, corresponding to HTTP PATCH
requests.delete() Submit delete request to HTML page, corresponding to HTTP DELETE
requests.get()
#获取HTML网页的主要方法,对应于HTTP的GET
r = requests.get(url, parms=None, **kwargs)
#url		:拟获取页面的url链接
#params		:url中的额外参数,字典或字节流格式(可选)
#**kwargs	:12个控制访问的参数,均为可选项
12 parameters Parameter meaning
data Dictionary, byte sequence or file object as the content of Request
json JSON format data as the content of Request
headers Dictionary, HTTP custom header
cookies Dictionary or CookieJar, Cookie in Request
auth Tuple, support HTTP authentication
files Dictionary type, transfer files
timeout Set the timeout time, in seconds
proxies Dictionary type, set access to proxy server, can increase login authentication
allow_redirects Ture / False, True by default, redirect switch
stream True / false, the default is True, get content immediately download switch
verify True / False, True by default, SSL certificate switch
cert Local SSL certificate path
#构造一个向服务器请求资源的Request对象:requests.get()
#返回一个包含服务器资源的Response对象:r
Response attribute Attribute meaning
r.status_code HTTP request return status
r.text The string form of the HTTP response content, that is, the page content corresponding to the url
r.encoding Response encoding method guessed from the HTTP header. If there is no charset in the header, it is considered to be ISO-8859-1
r.apparent_encoding Response content encoding method analyzed from content (optional)
r.content Binary form of HTTP response content
Requests library exception type Abnormal meaning
requests.ConnectionError Network connection errors, such as DNS query failure, connection refused, etc.
requests.HTTPError HTTP error exception
requests.URLRequired URL missing exception
requests.TooManyRedirects Exceeding the maximum number of redirects, a redirect exception is generated
requests.ConnectTimeout Connection to remote server timeout exception
requests.Timeout Request URL timed out
r.raise_for_status()
#如果不是200,产生异常requests.HTTPError

(3)status_code

#HTTP: Status 200 – 服务器成功返回网页
#HTTP: Status 404 – 请求的网页不存在
#HTTP: Status 503 – 服务不可用
-------------------------------------------
HTTP Status 2xx  (成功)
表示成功处理了请求的状态代码;

详细代码说明:
HTTP Status 200 (成功)
-> 服务器已成功处理了请求。 通常,这表示服务器提供了请求的网页。
HTTP Status 201 (已创建)
-> 请求成功并且服务器创建了新的资源。
HTTP Status 202 (已接受)
-> 服务器已接受请求,但尚未处理。
HTTP Status 203 (非授权信息)
-> 服务器已成功处理了请求,但返回的信息可能来自另一来源。
HTTP Status 204 (无内容)
-> 服务器成功处理了请求,但没有返回任何内容。
HTTP Status 205 (重置内容)
-> 服务器成功处理了请求,但没有返回任何内容。
HTTP Status 206 (部分内容)
-> 服务器成功处理了部分 GET 请求。
-------------------------------------------
HTTP Status 4xx (请求错误)
这些状态代码表示请求可能出错,妨碍了服务器的处理;

详细代码说明:
HTTP Status 400 (错误请求) 
->服务器不理解请求的语法。
HTTP Status 401 (未授权) 
->请求要求身份验证。 对于需要登录的网页,服务器可能返回此响应。
HTTP Status 403 (禁止)
-> 服务器拒绝请求。
HTTP Status 404 (未找到) 
->服务器找不到请求的网页。
HTTP Status 405 (方法禁用) 
->禁用请求中指定的方法。
HTTP Status 406 (不接受) 
->无法使用请求的内容特性响应请求的网页。
HTTP Status 407 (需要代理授权) 
->此状态代码与 401(未授权)类似,但指定请求者应当授权使用代理。
HTTP Status 408 (请求超时) 
->服务器等候请求时发生超时。
HTTP Status 409 (冲突) 
->服务器在完成请求时发生冲突。 服务器必须在响应中包含有关冲突的信息。
HTTP Status 410 (已删除)
-> 如果请求的资源已永久删除,服务器就会返回此响应。
HTTP Status 411 (需要有效长度) 
->服务器不接受不含有效内容长度标头字段的请求。
HTTP Status 412 (未满足前提条件) 
->服务器未满足请求者在请求中设置的其中一个前提条件。
HTTP Status 413 (请求实体过大) 
->服务器无法处理请求,因为请求实体过大,超出服务器的处理能力。
HTTP Status 414 (请求的 URI 过长) 请求的 URI(通常为网址)过长,服务器无法处理。
HTTP Status 415 (不支持的媒体类型) 
->请求的格式不受请求页面的支持。
HTTP Status 416 (请求范围不符合要求) 
->如果页面无法提供请求的范围,则服务器会返回此状态代码。
HTTP Status 417 (未满足期望值) 
->服务器未满足”期望”请求标头字段的要求。
-------------------------------------------
HTTP Status 5xx (服务器错误)
这些状态代码表示服务器在尝试处理请求时发生内部错误。 这些错误可能是服务器本身的错误,而不是请求出错;

代码详细及说明:
HTTP Status 500 (服务器内部错误) 
->服务器遇到错误,无法完成请求。
HTTP Status 501 (尚未实施) 
->服务器不具备完成请求的功能。 例如,服务器无法识别请求方法时可能会返回此代码。
HTTP Status 502 (错误网关) 
->服务器作为网关或代理,从上游服务器收到无效响应。
HTTP Status 503 (服务不可用)
-> 服务器目前无法使用(由于超载或停机维护)。 通常,这只是暂时状态。
HTTP Status 504 (网关超时) 
->服务器作为网关或代理,但是没有及时从上游服务器收到请求。
HTTP Status 505 (HTTP 版本不受支持)
-> 服务器不支持请求中所用的 HTTP 协议版本。

#Universal code framework for crawling web pages #

#爬取网页的通用代码框架
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))
Published 10 original articles · Like1 · Visits 141

Guess you like

Origin blog.csdn.net/qq_39419113/article/details/105489591