Python - 在http响应流中寻找

Mos*_*vah 11 python http

使用urllibs(或urllibs2)并想要我想要的东西是没有希望的.有解决方案吗

Bla*_*air 23

我不确定C#实现是如何工作的,但是,由于互联网流通常是不可搜索的,我猜测它会将所有数据下载到本地文件或内存中对象,并从那里进行搜索.Python的等价物就像Abafei建议的那样,将数据写入文件或StringIO并从那里寻找.

但是,如果您对Abafei的回答所表达的评论表明,您只想检索文件的特定部分(而不是通过返回的数据进行后退和转发),则还有另一种可能性.urllib2可用于检索网页的某个部分(或HTTP术语中的"范围"),前提是服务器支持此行为.

range

向服务器发送请求时,请求的参数在各种标头中给出.其中之一是Range标题,在RFC2616(定义HTTP/1.1的规范)的第14.35节中定义.此标头允许您执行诸如从第10,000个字节开始检索所有数据或从1,000个字节和1,500个字节之间检索数据的操作.

服务器支持

不要求服务器支持范围检索.如果某些服务器支持范围,则它们将返回Accept-Ranges标题(RFC2616的第14.5节)以及对报告的响应.可以使用HEAD请求来检查.但是,没有特别需要这样做; 如果服务器不支持范围,它将返回整个页面,然后我们可以像以前一样在Python中提取所需的数据部分.

检查是否返回了范围

如果服务器返回一个范围,它必须发送Content-Range标题(RFC2616的第14.16节)以及响应.如果这在响应的标题中出现,我们知道返回了一个范围; 如果它不存在,则返回整个页面.

使用urllib2实现

urllib2允许我们向请求添加标头,从而允许我们向服务器询问范围而不是整个页面.以下脚本在命令行上获取URL,起始位置和(可选)长度,并尝试检索页面的给定部分.

import sys
import urllib2

# Check command line arguments.
if len(sys.argv) < 3:
    sys.stderr.write("Usage: %s url start [length]\n" % sys.argv[0])
    sys.exit(1)

# Create a request for the given URL.
request = urllib2.Request(sys.argv[1])

# Add the header to specify the range to download.
if len(sys.argv) > 3:
    start, length = map(int, sys.argv[2:])
    request.add_header("range", "bytes=%d-%d" % (start, start + length - 1))
else:
    request.add_header("range", "bytes=%s-" % sys.argv[2])

# Try to get the response. This will raise a urllib2.URLError if there is a
# problem (e.g., invalid URL).
response = urllib2.urlopen(request)

# If a content-range header is present, partial retrieval worked.
if "content-range" in response.headers:
    print "Partial retrieval successful."

    # The header contains the string 'bytes', followed by a space, then the
    # range in the format 'start-end', followed by a slash and then the total
    # size of the page (or an asterix if the total size is unknown). Lets get
    # the range and total size from this.
    range, total = response.headers['content-range'].split(' ')[-1].split('/')

    # Print a message giving the range information.
    if total == '*':
        print "Bytes %s of an unknown total were retrieved." % range
    else:
        print "Bytes %s of a total of %s were retrieved." % (range, total)

# No header, so partial retrieval was unsuccessful.
else:
    print "Unable to use partial retrieval."

# And for good measure, lets check how much data we downloaded.
data = response.read()
print "Retrieved data size: %d bytes" % len(data)
Run Code Online (Sandbox Code Playgroud)

使用这个,我可以检索Python主页的最后2,000个字节:

blair@blair-eeepc:~$ python retrieverange.py http://www.python.org/ 17387
Partial retrieval successful.
Bytes 17387-19386 of a total of 19387 were retrieved.
Retrieved data size: 2000 bytes
Run Code Online (Sandbox Code Playgroud)

或者从主页中间400字节:

blair@blair-eeepc:~$ python retrieverange.py http://www.python.org/ 6000 400
Partial retrieval successful.
Bytes 6000-6399 of a total of 19387 were retrieved.
Retrieved data size: 400 bytes
Run Code Online (Sandbox Code Playgroud)

但是,Google主页不支持范围:

blair@blair-eeepc:~$ python retrieverange.py http://www.google.com/ 1000 500
Unable to use partial retrieval.
Retrieved data size: 9621 bytes
Run Code Online (Sandbox Code Playgroud)

在这种情况下,在进行任何进一步处理之前,有必要在Python中提取感兴趣的数据.