Python 仅获取响应头, 不获取实体的实例
- 更新时间:2022-07-04 09:08:36
- 编辑:弓安安
Python Just get Response Headers, not get content.
1. Use HEAD method
>>> import requests >>> res = requests.head("http://www.baidu.com/") >>> req.head("https://www.baidu.com/").headers {'Content-Encoding': 'gzip', 'Server': 'bfe/1.0.8.18', 'Last-Modified': 'Mon, 13 Jun 2016 02:50:08 GMT', 'Connection': 'Keep-Alive', 'Pragma': 'no-cache', 'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Date': 'Fri, 13 Oct 2017 04:36:20 GMT', 'Content-Type': 'text/html'} >>> res.ok True >>> res.content '' # 但是会遇到一些问题, 比如, 服务器不支持 HEAD, 或者拒绝 HEAD. # 如下情况就被拒绝 # >>> res = req.head("https://www.douban.com/subject/1/") >>> res <Response [403]> >>> res.ok False >>> res.content '' >>> res.headers {'Content-Encoding': 'gzip', 'Keep-Alive': 'timeout=30', 'Server': 'dae', 'Connection': 'keep-alive', 'Date': 'Fri, 13 Oct 2017 04:39:00 GMT', 'Content-Type': 'text/html'}
不是很通用, 因为有些服务器不支持.
2. Use urllib
import urllib >>> res = urllib.urlopen("http://127.0.0.1:8000/git.exe") >>> res.url 'http://127.0.0.1:8000/git.exe' >>> res.headers.headers ['Server: SimpleHTTP/0.6 Python/2.7.10\r\n', 'Date: Fri, 13 Oct 2017 06:06:37 GMT\r\n', 'Content-type: application/x-msdownload\r\n', 'Content-Length: 7569408\r\n', 'Last-Modified: Fri, 16 Dec 2016 07:09:32 GMT\r\n'] >>> len(r.read()) 7569408 # urllib 只有在调用 read/readline/readlines 的时候才会从 web 服务器读取数据. # 源码可以在 urllib/httplib 中找到. # urllib.py def urlopen(url, ...): opener = FancyURLopener() return opener.open(url) class FancyURLopener(URLopener).open(): getattr(self, name)(url) class URLopener.open_http(): errcode, errmsg, headers = h.getreply() if(200 <= errcode < 300): return addinfourl(fp, headers, "http:" + url, errcode) else: if data is None: return self.http_error(url, fp, errcode, errmsg, headers) else: return self.http_error(url, fp, errcode, errmsg, headers, data) class URLopener.http_error(): return method(url, fp, errcode, errmsg, headers) class FancyURLopener.http_error_default(): return addinfourl(fp, headers, "http:" + url, errcode) class addinfourl(addbase): # 代码中并没有对 fp 做任何操作,包括读写. class addbase.__init __(): self.fp = fp self.read = self.fp.read self.readline = self.fp.readline if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines self.fileno = self.fp.fileno # ... ...
可以看到, urllib.open 最终返回了 addbase, addbase 中没有对 socket 做任务处理, 不会有任何读写. 之后显示调用 read/readline/readlines, 才会从 web 服务器读取数据.
图 1. 初始化网络.
图 2. urlopen() 之后
图 3. read() 之后
3. Use socket
看过 urllib 之后, 可以使用 socket 写一个方法, 只获取 header.
import socket import ssl _timeout = 10 socket.setdefaulttimeout(_timeout) def get_header(host, port=80, uri="/", method="GET", user_ssl=False): # 这里可以再扩充一下, 支持 headers conn = None header = """%s %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36\r\n\r\n""" % ( method, uri, host) if user_ssl: ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) _socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn = ssl_context.wrap_socket(_socket, server_hostname=host) conn.connect((host, port)) conn.send(header) else: conn = socket.create_connection((host, port), _timeout) conn.sendall(header) text = "" while True: if "\r\n\r\n" in text: break buff = conn.recv(10) text += buff # print buff conn.close() return text.split("\r\n\r\n")[0] if __name__ == '__main__': print get_header("www.douban.com", uri="/subject/27076001/") print print get_header("www.douban.com", uri="/subject/27076001/", port=443, user_ssl=True)
➜ 76[14:48:20]zhipeng@zhipeng-MacBook ~/demo/python �� $ python test_header.py HTTP/1.1 301 Moved Permanently Date: Fri, 13 Oct 2017 06:48:23 GMT Content-Type: text/html Content-Length: 178 Connection: close Location: https://www.douban.com/subject/27076001/ Server: dae HTTP/1.1 302 Moved Temporarily Server: ADSSERVER/45863 Date: Fri, 13 Oct 2017 06:48:23 GMT Content-Type: text/html Transfer-Encoding: chunked Connection: close Location: https://sec.douban.com/b?r=https%3A%2F%2Fwww.douban.com%2Fsubject%2F27076001%2F Strict-Transport-Security: max-age=15552000; Set-Cookie: __ads_session=uY8l3pLW/AjCKJ8Y4wA=; domain=.douban.com; path=/ X-Powered-By-ADS: uni-jnads-1-02 ➜ 77[14:48:23]zhipeng@zhipeng-MacBook ~/demo/python �� $
参考
<< Python socket server handle HTTPS request >> (https://stackoverflow.com/questions/32062925/python-socket-server-handle-https-request)
以上这篇Python 仅获取响应头, 不获取实体的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持码农之家。
相关教程
-
实例解析Python3 如何利用requests 库进行post携带账号密码请求数据
今天小编就为大家分享一篇Python3 利用requests 库进行post携带账号密码请求数据的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
发布时间:2020-02-11
-
python出现的时间
python出现即发行时间是在1991年。Python是一种广泛使用的解释型、高级编程、通用型编程语言,由吉多·范罗苏姆创造,第一版发布于1991年。可以视之为一种改良(加入一些其他编程语言的优点
发布时间:2021-05-24
-
python3爬取TOP500的音乐信息的代码详解
今天小编就为大家分享一篇python3 实现爬取TOP500的音乐信息并存储到mongoDB数据库中,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
发布时间:2020-02-04
-
python判断文件是否存在的方法
python判断文件是否存在,可以使用os模块中的os.path.exists()方法用于检验文件;或者在程序中直接使用open()方法来检查文件是否存在和可读写;还可以使用pathlib模块检验文件是否存在。
发布时间:2020-01-27
-
《Python编程:从入门到实践》第十一章:测试代码
11-1 城市和国家 编写一个函数,它接受两个形参:一个城市名和一个国家名。这个函数返回一个格式为City, Country 的字符串,如Santiago, Chile 。将 这个函数存储在一个名为city_functions.py的模块中。 创建一个名为test_cities.py的程序,对刚编写的函数进行测试(别忘了,你需要导入模块unittest 以及要测试的函数)。编写一个名为test_city_country() 的 方法,核实使用类似于santiago 和chile 这样
发布时间:2018-12-01
-
《Python编程:从入门到实践》第三章:列表简介
什么是列表呢? 官方说明就是由一些列按特点顺序排列的元素组成。其实可以看出很多个字符串的有序组合吧,里面的内容可以随时的删除,增加,修改。 下面这个就是一个列表,python打印列表的时候会将中括号和引号打印出来的 name = [liubin,liujian,liuliu] print (name)[liubin, liujian, liuliu] 有序的列表 和大多数编程语言一样,列表的第一个元素的索引是0,而不是1。如果要输出最后一个
发布时间:2018-12-01
-
分享python爬虫headers设置后无效的解决方案
这篇文章主要为大家详细介绍了python爬虫headers设置后无效的解决方案,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
发布时间:2020-02-14