python超链接打开远程文件_Python使用HTTP在远程文件上搜索

1586010002-jmsa.png

How do I seek to a particular position on a remote (HTTP) file so I can download only that part?

Lets say the bytes on a remote file were: 1234567890

I wanna seek to 4 and download 3 bytes from there so I would have: 456

and also, how do I check if a remote file exists?

I tried, os.path.isfile() but it returns False when I'm passing a remote file url.

解决方案

If you are downloading the remote file through HTTP, you need to set the Range header.

Check in this example how it can be done. Looks like this:

myUrlclass.addheader("Range","bytes=%s-" % (existSize))

EDIT: I just found a better implementation. This class is very simple to use, as it can be seen in the docstring.

class HTTPRangeHandler(urllib2.BaseHandler):

"""Handler that enables HTTP Range headers.

This was extremely simple. The Range header is a HTTP feature to

begin with so all this class does is tell urllib2 that the

"206 Partial Content" reponse from the HTTP server is what we

expected.

Example:

import urllib2

import byterange

range_handler = range.HTTPRangeHandler()

opener = urllib2.build_opener(range_handler)

# install it

urllib2.install_opener(opener)

# create Request and set Range header

req = urllib2.Request('http://www.python.org/')

req.header['Range'] = 'bytes=30-50'

f = urllib2.urlopen(req)

"""

def http_error_206(self, req, fp, code, msg, hdrs):

# 206 Partial Content Response

r = urllib.addinfourl(fp, hdrs, req.get_full_url())

r.code = code

r.msg = msg

return r

def http_error_416(self, req, fp, code, msg, hdrs):

# HTTP's Range Not Satisfiable error

raise RangeError('Requested Range Not Satisfiable')

Update: The "better implementation" has moved to github: excid3/urlgrabber in the byterange.py file.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值