Home  >  Article  >  Backend Development  >  How to Use urllib2 with a Proxy?

How to Use urllib2 with a Proxy?

DDD
DDDOriginal
2024-10-26 17:37:02928browse

How to Use urllib2 with a Proxy?

Using a Proxy with urllib2

When working with urllib2, there are situations where you may need to connect to the internet through a proxy server. Here's how you can use urllib2 to establish such a connection:

Question:

I want to open URLs using urllib2 with a proxy. I've tried using the following:

<code class="python">site = urllib2.urlopen('http://google.com', proxies={'http':'127.0.0.1'})</code>

but it doesn't seem to work. Is there a specific function I need to use to configure the proxy?

Answer:

To use a proxy with urllib2, you can follow these steps:

  1. Create a ProxyHandler object and specify the desired proxy settings:
<code class="python">proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})</code>
  1. Create an Opener object using the ProxyHandler:
<code class="python">opener = urllib2.build_opener(proxy)</code>
  1. Install the opener as the default opener for urllib2:
<code class="python">urllib2.install_opener(opener)</code>
  1. Use the installed opener to open the URL:
<code class="python">urllib2.urlopen('http://www.google.com')</code>

By following these steps, you can configure urllib2 to use the specified proxy server when making requests.

The above is the detailed content of How to Use urllib2 with a Proxy?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn