Reputation: 141
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
Upvotes: 4
Views: 8592
Reputation: 41
İ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.)
Upvotes: 0
Reputation: 98961
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)
Upvotes: 8
Reputation: 1562
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.
Upvotes: -3