对于给定的websi,请求流超时不起作用

2024-10-01 04:46:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下功能,从域名主页下拉内容。但它不适用于站点http://mywatchedmovies.com。在

import requests

def fetch_url(url, timeout, max_content, headers):

    r = requests.get(url, stream=True, timeout=timeout, headers=headers)
    r.raise_for_status()

    if int(r.headers.get('Content-Length',0)) > max_content:
        raise ValueError('response too large')

    content = r.raw.read(max_content+1, decode_content=True)
    if len(content) > max_content:
        print(url)
        raise ValueError('Too large a response')
    return {'url':url,'content':content,'status_code':r.status_code}

timeout = 10
max_content = 5000000
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}

fetch_url('http://mywatchedmovies.com', timeout, max_content, headers)

如果我改变函数来得到head,那么它会触发超时,这是很好的。但我需要这个功能是非常高的性能,我宁愿不拿头,然后拉下来的主页。或者我可以在不降低性能的情况下处理请求吗?在


Tags: 功能comhttpurlgetstatustimeout主页