我不确定 C# 实现是如何工作的,但是,由于 Internet 流通常不可搜索,我猜它会将所有数据下载到本地文件或内存对象并从那里搜索。与此等效的 Python 将按照 Abafei 的建议将数据写入文件或 StringIO 并从那里查找。
但是,如果正如您对 Abafei 回答的评论所暗示的那样,您只想检索文件的特定部分(而不是通过返回的数据来回查找),还有另一种可能性。 urllib2 可用于检索网页的某个部分(或 HTTP 术语中的“范围”),前提是服务器支持此行为。
range 标头
当您向服务器发送请求时,请求的参数在各种标头中给出。其中之一是Range 标头,在section 14.35 of RFC2616(定义HTTP/1.1 的规范)中定义。此标头允许您执行诸如检索从第 10,000 个字节开始的所有数据或字节 1,000 到 1,500 之间的数据等操作。
服务器支持
服务器不需要支持范围检索。一些服务器将返回 Accept-Ranges 标头 (section 14.5 of RFC2616) 以及响应以报告它们是否支持范围。这可以使用 HEAD 请求进行检查。但是,没有特别需要这样做;如果服务器不支持范围,它将返回整个页面,然后我们可以像以前一样在 Python 中提取所需的数据部分。
检查是否返回范围
如果服务器返回一个范围,它必须将 Content-Range 标头 (section 14.16 of RFC2616) 与响应一起发送。如果这出现在响应的标头中,我们就知道返回了一个范围;如果不存在,则返回整个页面。
使用 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)
使用它,我可以检索 Python 主页的最后 2000 个字节:
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
或首页中间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
但是,Google 主页不支持范围:
blair@blair-eeepc:~$ python retrieverange.py http://www.google.com/ 1000 500
Unable to use partial retrieval.
Retrieved data size: 9621 bytes
在这种情况下,有必要在 Python 中提取感兴趣的数据,然后再进行任何进一步处理。