简体   繁体   中英

Catch proxy errors on requests python

I'm new on python so I'm having some trouble. I'm trying to build a tool that posts data to an external server with proxy. I have it working, but the problem is I don't know how to catch the proxy connection error and print something else. The code I wrote is:

import requests
from bs4 import BeautifulSoup

headers = {
    "User-Agent": "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11",
    "Content-Type": "application/json"
}
proxies = { 
    "https": "https://244.324.324.32:8081",
}
data = {"test": "test"}
r = requests.post("https://example.com/page", proxies=proxies, json=data, headers=headers)
print(r.text)

How can I print, for example "Proxy Connection Error", when the proxy is dead (not connecting/working) or something like this. This is my first time using python so I'm having trouble.

Thank You

The accepted answer didn't work for me.
I had to use requests.exceptions.ProxyError , ie:

try:
    req = requests.post(...)
except requests.exceptions.ProxyError as err:
    print("Proxy Error", err)

İf you dont know the exception error, You can do run this first

try:
    req = requests.post(...)
except requests.exceptions.ProxyError as err:
    print(sys.exc_info()[0])

This gives you the error name, and then you can add your code this err. (Sometimes you need to import the exception error.)

You can use a try/except block to catch a connection error:

try:
  r = requests.post("https://example.com/page", proxies=proxies, json=data, headers=headers)
except requests.exceptions.ConnectionError:
  print "Proxy Connection Error"
print(r.text)

In the code above, if requests.post raises a ConnectionError , the except block will catch it and print out the Proxy Connection Error message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM