Python 仅获取响应头, 不获取实体的实例


Posted in Python onAugust 21, 2019

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. 初始化网络.

Python 仅获取响应头, 不获取实体的实例

图 2. urlopen() 之后

Python 仅获取响应头, 不获取实体的实例

图 3. read() 之后

Python 仅获取响应头, 不获取实体的实例

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 仅获取响应头, 不获取实体的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python翻译软件实现代码(使用google api完成)
Nov 26 Python
python抓取网页图片示例(python爬虫)
Apr 27 Python
python类继承与子类实例初始化用法分析
Apr 17 Python
基于python中pygame模块的Linux下安装过程(详解)
Nov 09 Python
基于Python实现的微信好友数据分析
Feb 26 Python
python生成每日报表数据(Excel)并邮件发送的实例
Feb 03 Python
Python实现带下标索引的遍历操作示例
May 30 Python
Python正则表达式匹配和提取IP地址
Jun 06 Python
使用Python制作表情包实现换脸功能
Jul 19 Python
matlab、python中矩阵的互相导入导出方式
Jun 01 Python
浅谈opencv自动光学检测、目标分割和检测(连通区域和findContours)
Jun 04 Python
Python tkinter制作单机五子棋游戏
Sep 14 Python
详解用Python为直方图绘制拟合曲线的两种方法
Aug 21 #Python
Python 使用指定的网卡发送HTTP请求的实例
Aug 21 #Python
Python turtle绘画象棋棋盘
Aug 21 #Python
Python随机函数库random的使用方法详解
Aug 21 #Python
Django+zTree构建组织架构树的方法
Aug 21 #Python
python的移位操作实现详解
Aug 21 #Python
基于Python的微信机器人开发 微信登录和获取好友列表实现解析
Aug 21 #Python
You might like
将数组写入txt文件 var_export
2009/04/21 PHP
php中在PDO中使用事务(Transaction)
2011/05/14 PHP
yii的CURD操作实例详解
2014/12/04 PHP
PHP如何获取Cookie并实现模拟登录
2020/07/16 PHP
实现png图片和png背景透明(支持多浏览器)的方法
2009/09/08 Javascript
jQuery 选择器理解
2010/03/16 Javascript
javascript中节点的最近的相关节点访问方法
2013/03/20 Javascript
JS Map 和 List 的简单实现代码
2013/07/08 Javascript
jQuery实现自动滚动到页面顶端的方法
2015/05/22 Javascript
javascript实现在下拉列表中显示多级树形菜单的方法
2015/08/12 Javascript
基于MVC4+EasyUI的Web开发框架形成之旅之界面控件的使用
2015/12/16 Javascript
js下将金额数字每三位一逗号分隔
2016/02/19 Javascript
JQuery点击行tr实现checkBox选中的简单实例
2016/05/26 Javascript
详解Jquery的事件操作和文档操作
2016/12/19 Javascript
ZeroClipboard.js使用一个flash复制多个文本框
2017/06/19 Javascript
微信小程序引用公共js里的方法的实例详解
2017/08/17 Javascript
jQuery轻量级表单模型验证插件
2018/10/15 jQuery
Vue+Element UI+Lumen实现通用表格分页功能
2019/02/02 Javascript
javascript中数组的常用算法深入分析
2019/03/12 Javascript
Vue——前端生成二维码的示例
2020/12/19 Vue.js
python字符串替换示例
2014/04/24 Python
讲解Python中fileno()方法的使用
2015/05/24 Python
Python3的urllib.parse常用函数小结(urlencode,quote,quote_plus,unquote,unquote_plus等)
2016/09/18 Python
Python中如何获取类属性的列表
2016/12/26 Python
python3将视频流保存为本地视频文件
2018/06/20 Python
Python GUI库PyQt5图形和特效样式QSS介绍
2020/02/25 Python
python 使用递归回溯完美解决八皇后的问题
2020/02/26 Python
python 爬虫之selenium可视化爬虫的实现
2020/12/04 Python
多视角3D可旋转的HTML5 Logo动画
2016/03/02 HTML / CSS
英国男女奢华内衣和泳装购物网站:Figleaves
2017/01/28 全球购物
Farfetch香港官网:汇集全球时尚奢侈品购物平台
2017/11/26 全球购物
英国最大的海报商店:GB Posters
2018/03/20 全球购物
Linux的文件类型
2012/03/07 面试题
技校毕业生自荐书
2014/05/23 职场文书
Python列表的索引与切片
2022/04/07 Python
Redis实战高并发之扣减库存项目
2022/04/14 Redis