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脚本分享
Apr 21 Python
详解Django通用视图中的函数包装
Jul 21 Python
Python首次安装后运行报错(0xc000007b)的解决方法
Oct 18 Python
Python实现并行抓取整站40万条房价数据(可更换抓取城市)
Dec 14 Python
python flask 多对多表查询功能
Jun 25 Python
详解python实现读取邮件数据并下载附件的实例
Aug 03 Python
Python3解释器知识点总结
Feb 19 Python
Python中的异常处理try/except/finally/raise用法分析
Feb 28 Python
python__new__内置静态方法使用解析
Jan 07 Python
python无序链表删除重复项的方法
Jan 17 Python
在PyCharm中遇到pip安装 失败问题及解决方案(pip失效时的解决方案)
Mar 10 Python
django表单中的按钮获取数据的实例分析
Jul 31 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
关于PHP中Object对象的笔记分享
2011/06/28 PHP
php函数array_merge用法一例(合并同类数组)
2013/02/03 PHP
8个PHP程序员常用的功能汇总
2014/12/18 PHP
php mysql like 实现多关键词搜索的方法
2016/10/29 PHP
PHP使用CURL实现下载文件功能示例
2019/06/03 PHP
PHP检查文件是否存在,不存在自动创建及读取文件内容操作示例
2020/01/23 PHP
基于jQuery的倒计时插件代码
2011/05/07 Javascript
20款效果非常棒的 jQuery 插件小结分享
2011/11/18 Javascript
Javascript 鼠标移动上去 滑块跟随效果代码分享
2013/11/23 Javascript
仿百度联盟对联广告实现代码
2014/08/30 Javascript
JS实现从连接中获取youtube的key实例
2015/07/02 Javascript
js实现一个猜数字游戏
2017/03/31 Javascript
JavaScript中in和hasOwnProperty区别详解
2017/08/04 Javascript
js数组实现权重概率分配
2017/09/12 Javascript
angularJS开发注意事项
2018/05/26 Javascript
基于Angular中ng-controller父子级嵌套的相关属性详解
2018/10/08 Javascript
vue组件传值的实现方式小结【三种方式】
2020/02/05 Javascript
python在线编译器的简单原理及简单实现代码
2018/02/02 Python
Python+PyQt5实现美剧爬虫可视工具的方法
2019/04/25 Python
Python入门Anaconda和Pycharm的安装和配置详解
2019/07/16 Python
Python 获取指定文件夹下的目录和文件的实现
2019/08/30 Python
Python中的 ansible 动态Inventory 脚本
2020/01/19 Python
Tensorflow安装问题: Could not find a version that satisfies the requirement tensorflow
2020/04/20 Python
Python基于requests实现模拟上传文件
2020/04/21 Python
python获取时间戳的实现示例(10位和13位)
2020/09/23 Python
Python tempfile模块生成临时文件和临时目录
2020/09/30 Python
Django filter动态过滤与排序实现过程解析
2020/11/26 Python
python中pop()函数的语法与实例
2020/12/01 Python
解决python 执行shell命令无法获取返回值的问题
2020/12/05 Python
房地产销售大学生自我评价分享
2013/11/11 职场文书
会计职业生涯规划书
2014/01/13 职场文书
公务员转正鉴定材料
2014/02/11 职场文书
借名购房协议书范本
2014/10/06 职场文书
公务员年度考核登记表个人总结
2015/02/12 职场文书
nginx优化的六点方法
2021/03/31 Servers
Eclipse+Java+Swing+Mysql实现电影购票系统(详细代码)
2022/01/18 Java/Android