天天看點

python http代理_使用HTTP PROXY - Python

即使沒有HTTP_PROXY環境變量,您也可以這樣做。試試這個樣本:

import urllib2

proxy_support = urllib2.ProxyHandler({"http":"http://61.233.25.166:80"})

opener = urllib2.build_opener(proxy_support)

urllib2.install_opener(opener)

html = urllib2.urlopen("http://www.google.com").read()

print html

在您的情況下,似乎代理伺服器似乎拒絕連接配接。

還有更多嘗試:

import urllib2

#proxy = "61.233.25.166:80"

proxy = "YOUR_PROXY_GOES_HERE"

proxies = {"http":"http://%s" % proxy}

url = "http://www.google.com/search?q=test"

headers={'User-agent' : 'Mozilla/5.0'}

proxy_support = urllib2.ProxyHandler(proxies)

opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1))

urllib2.install_opener(opener)

req = urllib2.Request(url, None, headers)

html = urllib2.urlopen(req).read()

print html

編輯2014: 這似乎是一個受歡迎的問題/答案。但是今天我會改用第三方requests子產品。

對于一個請求,隻需:

import requests

r = requests.get("http://www.google.com",

proxies={"http": "http://61.233.25.166:80"})

print(r.text)

對于多個請求,請使用Session對象,這樣您就不必proxies在所有請求中添加參數:

import requests

s = requests.Session()

s.proxies = {"http": "http://61.233.25.166:80"}

r = s.get("http://www.google.com")

print(r.text)