侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   196

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.okTrue>>> res.content''# 但是会遇到一些问题, 比如, 服务器不支持 HEAD, 或者拒绝 HEAD.# 如下情况就被拒绝#>>> res = req.head("https://www.douban.com/subject/1/")>>> res<Response [403]>>>> res.okFalse>>> 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.pydef 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 socketimport ssl_timeout = 10socket.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.pyHTTP/1.1 301 Moved PermanentlyDate: Fri, 13 Oct 2017 06:48:23 GMTContent-Type: text/htmlContent-Length: 178Connection: closeLocation: https://www.douban.com/subject/27076001/Server: daeHTTP/1.1 302 Moved TemporarilyServer: ADSSERVER/45863Date: Fri, 13 Oct 2017 06:48:23 GMTContent-Type: text/htmlTransfer-Encoding: chunkedConnection: closeLocation: https://sec.douban.com/b?r=https%3A%2F%2Fwww.douban.com%2Fsubject%2F27076001%2FStrict-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为直方图绘制拟合曲线的两种方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客