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

举个例子,把python官网抓下来:

import urllib.request

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

然后后就会在控制台看到输出的html文件的信息。

然后我们输出response的对象类型

print(type(response))

然后可以看到它是一个HTTPResponse对象

它主要包含

read(), readinto(), getheader(name), getheaders(), fileno()等方法

以及msg, version, reason, debuglevel, closed等属性

查看返回状态码

print(response.status)

输出 200, 表明请求成功。

查看请求头

import urllib.request

response = urllib.request.urlopen('https://www.python.org')
print(response.getheaders())

然后就会以元组列表的形式返回header中的值

[('Connection', 'close'), ('Content-Length', '49625'), ('Server', 'nginx'), ('Content-Type', 'text/html; charset=utf-8'), ('X-Frame-Options', 'DENY'), ('Via', '1.1 vegur, 1.1 varnish, 1.1 varnish'), ('Accept-Ranges', 'bytes'), ('Date', 'Fri, 27 Nov 2020 14:46:37 GMT'), ('Age', '358'), ('X-Served-By', 'cache-bwi5139-BWI, cache-tyo19946-TYO'), ('X-Cache', 'HIT, HIT'), ('X-Cache-Hits', '4, 250'), ('X-Timer', 'S1606488397.399488,VS0,VE0'), ('Vary', 'Cookie'), ('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]

如果只是想获得某一属性的返回值,比如获得server属性,那么就这样写

print(response.getheader('Server'))

返回的是 nginx, 说明服务器用的是nginx

你也可能喜欢

发表评论