Skip to main content
 首页 » 编程设计

python之如何从urllib读取 "break"

2025年05月04日15unruledboy

如果发生某些事件,我想在打开 url 时停止 read。问题是,我不知道该怎么做。 例如:

data = urllib.request.urlopen('http://google.com') 
readData = data.read() # How do I stop the reading if certain event occurs? 

谢谢

请您参考如下方法:

read() 接受一次读取多少字节的参数。例如。 data = read(4096) 一次只读取 4 kB。读取切片中的数据,并在每个切片后检查中断条件。或者如果这是 Not Acceptable 选项,则在不同的线程中运行读取循环。

在伪 Python 中它应该看起来像这样:

import urllib2 
 
CHUNKSIZE = 4096 
 
r = urllib2.urlopen('http://www.python.org') 
 
buffer = b'' 
 
while True: 
    chunk = r.read(CHUNKSIZE) 
    if not chunk: 
        break 
    if bad_thing_happened: 
        break 
 
    buffer += chunk