Python - 请求以静默方式失败

时间:2017-12-12 17:32:48

标签: python-requests

import requests

正在为我的所有请求正常工作,例如:

url = 'http://www.stackoverflow.com'
response = requests.get(url)

bur以下url不会返回任何结果:

url = 'http://www.billboard.com'
response = requests.get(url)

它停滞不前,无声地失败,什么也没有回来。

如何强制requests向我发送异常响应, 所以我可以知道我是否被列入黑名单?

2 个答案:

答案 0 :(得分:2)

请求不会因错误的HTTP响应而引发异常,但您可以使用raise_for_status手动引发HTTPError异常,例如:

response = requests.get(url)

response.raise_for_status()

另一个选项是status_code,它包含HTTP代码。

response = requests.get(url)

if response.status_code != 200:
    print('HTTP', response.status_code)
else: 
    print(response.text)

如果网站针对错误请求返回HTTP 200,但在响应正文中有错误消息或者没有正文,则您必须检查响应内容。

error_message = 'Nothing found'
response = requests.get(url)

if error_message in response.text or not response.text:
    print('Bad response')
else: 
    print(response.text)

如果网站响应时间过长,您可以为请求设置最大超时时间。如果该网站在该时间内没有响应,则会引发ReadTimeout例外。

try:
    response = requests.get(url, timeout=5)
except requests.exceptions.ReadTimeout:
    print('Request timed out')
else:
    print(response.text)

答案 1 :(得分:0)

使用:

import requesocks

#Initialize a new wrapped requests object
session = requesocks.session()

#Use Tor for both HTTP and HTTPS
session.proxies = {'http': 'socks5://localhost:9050', 
                   'https': 'socks5://localhost:9050'}

#fetch a page that shows your IP address
response = session.get('https://www.billboard.com')

print(response.text)

我能得到:

    raise ConnectionError(e)
requesocks.exceptions.ConnectionError: HTTPSConnectionPool(host='www.billboard.com', port=None): Max retries exceeded with url: https://www.billboard.com/