3

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

pgngp
  • 1,552
  • 5
  • 16
  • 26
William James
  • 101
  • 2
  • 7

3 Answers3

7

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)
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
0

İ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.)

-3

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.

pgngp
  • 1,552
  • 5
  • 16
  • 26