Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 449
William James Avatar asked Oct 25 '25 09:10

William James


1 Answers

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

try:
    req = requests.post(...)
except requests.exceptions.ProxyError as err:
    print("Proxy Error", err)
like image 132
Pedro Lobito Avatar answered Oct 27 '25 00:10

Pedro Lobito