HTTPS urllib2のを使用してログインします
-
20-08-2019 - |
質問
私は現在、Webページをダウンロードし、私は。何も凝っています。
に興味があるいくつかのデータを抽出し、小さなスクリプトを持っています現在、私はそうのようなページをダウンロードしています:
import commands
command = 'wget --output-document=- --quiet --http-user=USER --http-password=PASSWORD https://www.example.ca/page.aspx'
status, text = commands.getstatusoutput(command)
これは完璧に動作しますが、、私はそれはwgetの上の依存関係を削除しても意味がしようと思いました。私はurllib2のに上記を変換するのは簡単であるべきと思ったが、これまでのところ、私はゼロの成功を収めてきました。インターネットは完全なurllib2の例ですが、私は、HTTPSサーバを持つ単純なユーザ名とパスワードHTTP認証のための私の必要性に合致するものを見つけていません。
解決
要求のモジュールは、HTTP / HTTPSの能力に近代的なAPIを提供します。
import requests
url = 'https://www.someserver.com/toplevelurl/somepage.htm'
res = requests.get(url, auth=('USER', 'PASSWORD'))
status = res.status_code
text = res.text
他のヒント
こののは言う、それがまっすぐでなければなりません
あなただけのHTTP基本認証を使用する場合は説明するように、[など]長いお近くのPythonがSSLをサポートしているよう。
、あなたは、別のハンドラを設定する必要がありますここ
します。そこ例を引用ます:
import urllib2
theurl = 'http://www.someserver.com/toplevelurl/somepage.htm'
username = 'johnny'
password = 'XXXXXX'
# a great password
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
# this creates a password manager
passman.add_password(None, theurl, username, password)
# because we have put None at the start it will always
# use this username/password combination for urls
# for which `theurl` is a super-url
authhandler = urllib2.HTTPBasicAuthHandler(passman)
# create the AuthHandler
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
# All calls to urllib2.urlopen will now use our handler
# Make sure not to include the protocol in with the URL, or
# HTTPPasswordMgrWithDefaultRealm will be very confused.
# You must (of course) use it when fetching the page though.
pagehandle = urllib2.urlopen(theurl)
# authentication is now handled automatically for us
あなたがダイジェストを行う場合は、、あなたはいくつかの追加のヘッダーを設定する必要がありますが、彼らは関係なく、SSLの使用と同じです。 python + urllib2の+ HTTP +ダイジェストのためのGoogle のrel="noreferrer">の
乾杯、
urllib2のドキュメントは、基本認証での作業の例があります:
所属していません StackOverflow