Zjw_ML
Zjw_ML

Reputation: 71

How to use different ip proxy on the same program in urllib2 ?

The following code can use proxy as official documents

proxy_handler = urllib2.ProxyHandler({protocol : protocol + '://' + ip_proxies})
opener = urllib2.build_opener(proxy_handler)
urllib2.install_opener(opener)

But I want to use different proxy on different method

Use urllib2.install_opener() will set the global opener in urllib2, so that I can't use two different Proxy settings in the program.

How can I not to use install_opener to change global settings, but only opener directly call the open method instead of global urlopen methods ?

Upvotes: 2

Views: 482

Answers (1)

Zjw_ML
Zjw_ML

Reputation: 71

I have solved this problem. The key is use requests instead of urllib2, my bad.

import requests

s = requests.Session()
proxies = {
        'http': 'http://127.0.0.1:8087',
        'https': 'http://127.0.0.1:8087',
}
login_data = {
        'email': '[email protected]',
        'pass': 'mima',
}
r = s.get('https://www.facebook.com/login.php?login_attempt=1', proxies=proxies, verify=False)

requests Supported Features

  • International Domains and URLs
  • Keep-Alive & Connection Pooling
  • Sessions with Cookie Persistence
  • Browser-style SSL Verification
  • Basic/Digest Authentication
  • Elegant Key/Value Cookies
  • Automatic Decompression
  • Automatic Content Decoding
  • Unicode Response Bodies
  • Multipart File Uploads
  • HTTP(S) Proxy Support
  • Connection Timeouts
  • Streaming Downloads
  • .netrc Support
  • Chunked Requests
  • Thread-safety

Upvotes: 1

Related Questions