requests.exceptions.ConnectionError: Failed to establish a new connection: 0x05: Connection refused

1.2k views Asked by At

I know there are already alot of topics writing about this topic, but none could held me.

import mechanicalsoup

browser = mechanicalsoup.StatefulBrowser()
browser.set_user_agent(
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36')

proxies = dict(http='socks5://104.238.97.230:31800', https='socks5://104.238.97.230:31800')
res = browser.open('http://icanhazip.com/', proxies=proxies, verify=False)
# res = browser.open('http://icanhazip.com/')
print(res.content)

My proxy is working, there is no problem with it. If i redirect my python traffic through proxifier i get the result i want to see, but if i just try this code, i get an error.

I also tried it with try - except and a sleep, but it didn't worked for me. Anyone know a solution?

1

There are 1 answers

0
Oliver W On

This worked for me:

import mechanicalsoup
import socks
import socket


def create_connection(self, address, timeout=None, source_address=None):
    sock = socks.socksocket()
    sock.connect(address)
    return sock


socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '104.238.97.230', 31800)

# patch the socket module
socket.socket = socks.socksocket
socket.create_connection = create_connection

browser = mechanicalsoup.StatefulBrowser()
browser.set_user_agent(
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36')

proxies = dict(http='socks5://104.238.97.230:31800', https='socks5://104.238.97.230:31800')

res = browser.open('http://icanhazip.com/')
print(res.content)