指定方法、認証プロキシのためのpython httpしています。
質問
何が最良の方法を指定するプロキシとユーザー名とパスワードにhttp接続python?
解決
使用す:
import requests
proxies = {"http":"http://username:password@proxy_ip:proxy_port"}
r = requests.get("http://www.example.com/", proxies=proxies)
print(r.content)
と思うのでよりも簡単な構成の使用 urllib
.かわからないのはなぜ人々に愛用 urllib
います。
他のヒント
この作品は私にとって:
import urllib2
proxy = urllib2.ProxyHandler({'http': 'http://
username:password@proxyurl:proxyport'})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)
conn = urllib2.urlopen('http://python.org')
return_str = conn.read()
設定環境var名 http_proxy このように: http://username:password@proxy_url:port
最良の方法の代理人を通じて必要とする認証を使用 urllib2 をカスタムurlをオープナー、そして使用するすべてのご要望があればお聞かせくを通じて行います。ントに特に注意してください、ほとんどない組み込みのパスワードプロキシのurlは、pythonソースコードなものでないかぎりではquick hack).
import urllib2
def get_proxy_opener(proxyurl, proxyuser, proxypass, proxyscheme="http"):
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, proxyurl, proxyuser, proxypass)
proxy_handler = urllib2.ProxyHandler({proxyscheme: proxyurl})
proxy_auth_handler = urllib2.ProxyBasicAuthHandler(password_mgr)
return urllib2.build_opener(proxy_handler, proxy_auth_handler)
if __name__ == "__main__":
import sys
if len(sys.argv) > 4:
url_opener = get_proxy_opener(*sys.argv[1:4])
for url in sys.argv[4:]:
print url_opener.open(url).headers
else:
print "Usage:", sys.argv[0], "proxy user pass fetchurls..."
より複雑なプログラムで別のこれらの部品として適用(インスタンスを利用し、一パスワードマネージャの寿命のものとします。のpythonドキュメントが 次のような複雑なものとurllib2 うににも便利です。
またはインストールするのでは常に使用urllib2.urlopen(必要ありませんがいへの参照オープナー周辺):
import urllib2
url = 'www.proxyurl.com'
username = 'user'
password = 'pass'
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# None, with the "WithDefaultRealm" password manager means
# that the user/pass will be used for any realm (where
# there isn't a more specific match).
password_mgr.add_password(None, url, username, password)
auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
print urllib2.urlopen("http://www.example.com/folder/page.html").read()
この方法を使用urllib
import urllib.request
# set up authentication info
authinfo = urllib.request.HTTPBasicAuthHandler()
proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"})
# build a new opener that adds authentication and caching FTP handlers
opener = urllib.request.build_opener(proxy_support, authinfo,
urllib.request.CacheFTPHandler)
# install it
urllib.request.install_opener(opener)
f = urllib.request.urlopen('http://www.python.org/')
"""
所属していません StackOverflow