White school Python reptiles (11): urllib Basics (a)

Life is short, I used Python

The foregoing Portal:

White school Python Reptile (1): Opening

White Python crawler Science (2): Pre-preparation (a) is mounted substantially libraries

Getting Started with Linux pre-prepared base (B): white reptile learn Python (3)

Docker basis of pre-entry preparation (III): white reptile learn Python (4)

White school Python Reptile (5): pre-prepared (four) database infrastructure

White school Python Reptile (6): pre-prepared (E) crawler frame installation

White school Python reptiles (7): HTTP basic

White school Python reptiles (8): page basis

White school Python reptiles (9): Reptile basis

White school Python reptiles (10): Session and Cookies

introduction

See Benpian students have no combat very excited, after torture in front of ten basis of content, until finally the actual chapter, is there a feeling of excitement.

Think of the lyrics: wait until you finally ~ ~ ~

First, the official document addresses Sincerely:

Official documents Address: https://docs.python.org/3/library/urllib.html

In the previous pre-preparation, together we install a lot of third-party libraries request, before the introduction of these third-party libraries, we first introduce Python3 itself comes with a HTTP request library urllib.

urllib

urllib is a software package that contains several modules for processing the URL:

  • request: the request based on HTTP module.
  • error: exception handling module.
  • parse: modules for parsing the URL.
  • robotparser: identify the site in the robots.txt file.

urllib.request

If you learn how to say the fastest, of course, is to look at the official document, first resorted to address official documents.

urllib.request official document: https://docs.python.org/3/library/urllib.request.html#module-urllib.request

这里的解释是最权威了,并且目前已经提供了中文版本,不过那个翻译看起来像是机器翻译的,质量并不高。

如果实在看不懂,就只能看小编 XBB 了。

urlopen

urllib.request 模块提供了最基本的构造 HTTP 请求的方法,使用它可以模拟浏览器的一个请求发起过程,同时它还带有处理授权验证(authenticaton)、重定向(redirection)、浏览器Cookies以及其他内容。

语法:

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

这么厉害的模块当然是要赶紧尝试一下,首先我们使用它爬取一下小编的博客站:

import urllib.request

response = urllib.request.urlopen('https://www.geekdigging.com/')
print(response.read().decode('utf-8'))

运行结果小编这里就不展示,比较长。

短短的三行代码,我们就完成了网站源代码的抓取,是不是很简单。

当我们得到源代码之后,想要的链接、文本信息,都可以从中提取出来。

各位同学看到打印的内容,可以猜测一下这个内容是什么数据类型,会是字符串类型么?

使用 type() 看一下就知道了。

print(type(response))

结果:

<class 'http.client.HTTPResponse'>

urlopen 返回了一个 HTTPResponse 类型的对象。

官方文档对 HTTPResponse 的解释如下:

An HTTPResponse instance wraps the HTTP response from the server. It provides access to the request headers and the entity body. The response is an iterable object and can be used in a with statement.

大意是说 HTTPResponse 是对 HTTP 响应的包装。它提供了对请求头和请求体的访问。这个响应是一个可以迭代的对象。

HTTPResponse 主要包含 read() 、 readline() 、 getheader(name) 、 getheaders() 、 fileno() 等方法,以及 msg 、 version 、 status 、 reason 、 debuglevel 、 closed 等属性。

import urllib.request

# 获取HTTP协议版本号(10 for HTTP/1.0, 11 for HTTP/1.1)
print(response.version)

# 获取响应码
print(response.status)
print(response.getcode())

# 获取响应描述字符串
print(response.reason)

# 获取实际请求的页面url(防止重定向用)
print(response.geturl())

# 获取特定响应头信息
print(response.getheader(name="Content-Type"))
# 获取响应头信息,返回二元元组列表
print(response.getheaders())
# 获取响应头信息,返回字符串
print(response.info())

# 读取响应体
print(response.readline().decode('utf-8'))

结果有点长,小编就不贴了,各位同学可以自己运行一下。

data

data 用来指明发往服务器请求中的额外的参数信息, data 默认是 None ,此时以 GET 方式发送请求;当用户给出 data 参数的时候,改为 POST 方式发送请求。

来个示例吧,这里我们使用 httpbin 提供的测试接口,此项目为 postmanlabs 提供在 Github开源的项目, Github 地址为:https://github.com/postmanlabs/httpbin

import urllib.request
import urllib.parse

post_data = bytes(urllib.parse.urlencode({'name': 'geekdigging', 'hello':'world'}), encoding='utf8')
response = urllib.request.urlopen('https://httpbin.org/post', data = post_data)
print(response.read().decode('utf-8'))

值得注意的是,这里我们传递了两个参数,是以 dict 的方式传递的,它一定需要被转码成 bytes 字节流, 这里使用了 bytes() 方法,第一个参数是我们需要转换的字符串,第二个参数是编码方式。

这里我们请求的路径是 https://httpbin.org/post ,这个链接可以用来测试 POST 请求,它可以返回一些我们刚才请求的信息。

响应结果如下:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "hello": "world", 
    "name": "geekdigging"
  }, 
  "headers": {
    "Accept-Encoding": "identity", 
    "Content-Length": "28", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "Python-urllib/3.7"
  }, 
  "json": null, 
  "origin": "218.79.141.143, 218.79.141.143", 
  "url": "https://httpbin.org/post"
}

从返回的响应信息中,我们可以看到请求头的相关信息,如我们请求的数据类型 Content-Typeapplication/x-www-form-urlencoded ,这个代表了我们提交数据的方式是表单提交,还可以看到请求的来源 origin 是小编当前电脑的 ip 地址,可以看到我们提交的数据 form 等等的相关信息。

timeout

timeout 用于设置超时时间,单位为秒。

如果请求超出了设置的时间,还未响应,就会抛出异常。

我们看个小示例:

import urllib.request
import urllib.parse

response = urllib.request.urlopen('http://httpbin.org/get', timeout = 1)
print(response.read().decode('utf-8'))

我们先将超时时间设置成为 1s ,看下响应结果:

{
  "args": {}, 
  "headers": {
    "Accept-Encoding": "identity", 
    "Host": "httpbin.org", 
    "User-Agent": "Python-urllib/3.7"
  }, 
  "origin": "218.79.141.143, 218.79.141.143", 
  "url": "https://httpbin.org/get"
}

可以看到是正常响应的,我们将超时时间设置为 0.1s ,再看下结果:

import urllib.request
import urllib.parse

response = urllib.request.urlopen('http://httpbin.org/get', timeout = 0.1)
print(response.read().decode('utf-8'))

已经可以看到抛异常出来了:

Traceback (most recent call last):
...
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
...
urllib.error.URLError: <urlopen error timed out>

Process finished with exit code 1

内容有些多,小编省略了大量的内容。

我们可以看到,这里确实抛出了超时的异常,还有同学记得我们前面讲过的异常处理么,这时我们可以添加一个异常处理,将这个超时的异常捕获。

import urllib.request
import urllib.error
import socket

try:
    response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
    print(response.read().decode('utf-8'))
except urllib.error.URLError as e:
    if isinstance(e.reason, socket.timeout):
        print('请求超时啦~~~')
    else:
        print(e)

结果如下:

请求超时啦~~~

证明我们已经成功捕获到了请求超时的异常。

还有其他的几个参数: cafilecapathcadefault 用于实现可信任的 CA 证书的 HTTP 请求,一般很少使用, context ,用来实现 SSL 加密传输,一般也很少使用。

好了,本篇的内容就到这里结束,希望各位同学可以自己动手敲一下上面的示例代码。

示例代码

本系列的所有代码小编都会放在代码管理仓库 Github 和 Gitee 上,方便大家取用。

示例代码-Github

示例代码-Gitee

Guess you like

Origin www.cnblogs.com/babycomeon/p/11986966.html