>> req.head ;更新日期:2024/10/13.幽灵资源网,磁力链接,云盘下载,BT种子,CPU天梯,显卡天梯,UU加速器,阅读3.0,英雄联盟,怪物猎人,王者荣耀,绿色地狱合成表,无损音乐网,无损音乐下载网站,无损音乐免费下载,320Kmp3下载,无损音乐免费下载网站,音画欣赏,无损音乐,抖音神曲,发烧大碟,车载歌曲,试音天碟,WMA,WAV+CUE,WAV整轨,FLAC分轨,DSD黑胶,HI-FI试音,SACD-ISO,4K高清,高清电影下载,Magnet,Torrent,BitTorrent,迅雷快传,SUB,SRT,ASS/SSA,SUP,RARBG,TLF字幕,BluRay,x265,x264,DTS-HD,WEBRip,10BIT,HDR,DDP5.1,WEB-DL,1080p高清电影下载,中国高清网,高清电影,720p,1080p,MKV,AVI,蓝光原盘,3D高清,电影下载,qq飞车紫钻,序列号,破解版,注册机,绿色版,教程网,互联网资源,福利资源,网络流行语,高清电影,韩剧美剧,动漫资讯,游戏教程,LOL资讯视频,CF活动大全,LOL最新活动,CF实用技巧,DNF活动资讯,王者荣耀,技术教程,SEO教程,网络教程,破解软件,游戏软件,网站源码,易语言源码,安卓软件,汉化版,度盘,百度云盘,蓝奏,微云盘,网盘,无广告纯净版,不限速下载,去广告,修改器,VIP解析,SN,PSCS6,万圣节的新娘,MusicTag,百度文库,原神">

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

脚本专栏 发布日期:2024/10/13 浏览次数:1

正在浏览:Python 仅获取响应头, 不获取实体的实例

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)
"external nofollow" target="_blank" href="https://stackoverflow.com/questions/32062925/python-socket-server-handle-https-request"><< Python socket server handle HTTPS request  (https://stackoverflow.com/questions/32062925/python-socket-server-handle-https-request)

以上这篇Python 仅获取响应头, 不获取实体的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。