我试图指示一个URL是否包含流媒体.我想关闭连接,如果链接是一个流媒体链接。
stream=True
? 因为我只对 content-Type:'text/*'
我尝试了什么:我试着发送了头文件 Connection: close
但它没有停止流.我也试图发送头 Connection: Keep-Alive
和 Keep-Alive: timeout=5, max=1
我试着通过了 stream=False
但我收不到 request.text
.
我的尝试。
def ignore_stream():
with requests.get('https://google.com', timeout=5, stream=True) as r:
if 'Content-Type' in r.headers:
if 'audio' in r.headers['Content-Type'] or 'video' in r.headers['Content-Type']:
print(r.headers['Content-Type'])
print('streaming link .. close the connection')
r.close()
else:
print('text page .. get text content')
print(r.text)
if __name__ == '__main__':
ignore_stream()
上面的代码确实关闭了流媒体连接,但我担心,这对流媒体检测来说是不够的。
你的连接会因此而被关闭 with
语句,因为它正在调用 Response.close()
自动在语句末尾添加。没有必要做 r.close()
,只需留下语句做工作,或者删除它,自己做。
在发送请求时,用 stream
标榜 True
只会在一开始下载响应头文件(更多信息 此处). 这意味着,如果你只想要 text/**
响应(并将其余部分标记为 "流 "URL),此时你就可以实现了。请看下面的演示,如果适合你,请告诉我。
# using "with" statement
def ignore_stream_with():
with requests.get('https://google.com', timeout=5, stream=True) as r:
if 'Content-Type' in r.headers:
if 'audio' in r.headers['Content-Type'] or 'video' in r.headers['Content-Type']:
print(r.headers['Content-Type'])
print('Link detected as streaming... Leaving "with" to close the connection.')
else:
print('Link detected as text!')
print('Response content:')
print(r.text)
# do more stuff with your response...
pass
# NOT using "with" statement
def ignore_stream_without():
r = requests.get('https://google.com', timeout=5, stream=True)
if 'Content-Type' in r.headers:
if 'audio' in r.headers['Content-Type'] or 'video' in r.headers['Content-Type']:
print(r.headers['Content-Type'])
print('Link detected as streaming... Leaving "with" to close the connection.')
else:
print('Link detected as text!')
print('Response content:')
print(r.text)
# do more stuff with your response...
pass
# remember always to close the connection!
r.close()
if __name__ == '__main__':
ignore_stream()