HTTPS تسجيل الدخول مع urllib2
-
20-08-2019 - |
سؤال
ولدي حاليا برنامج نصي القليل الذي يقوم بتحميل صفحة ويب ومقتطفات بعض البيانات أنا مهتم. لا شيء يتوهم.
وحاليا أنا تحميل الصفحة مثل ذلك:
import commands
command = 'wget --output-document=- --quiet --http-user=USER --http-password=PASSWORD https://www.example.ca/page.aspx'
status, text = commands.getstatusoutput(command)
وعلى الرغم من أن هذا يعمل تماما، وأعتقد أنه من المنطقي أن إزالة الاعتماد على مجلد مشترك. وأعتقد أنه يجب أن يكون تافها لتحويل ما سبق إلى urllib2، ولكن حتى الآن لقد كان نجاح الصفر. الإنترنت هو أمثلة urllib2 كاملة، ولكن لم أجد أي شيء يطابق حاجتي لاسم المستخدم بسيط والتوثيق HTTP كلمة المرور مع خادم HTTPS.
المحلول
href="http://www.python-requests.org/en/latest/" الوحدة توفر واجهة برمجة تطبيقات الحديثة لالقدرات HTTP / HTTPS.
import requests
url = 'https://www.someserver.com/toplevelurl/somepage.htm'
res = requests.get(url, auth=('USER', 'PASSWORD'))
status = res.status_code
text = res.text
نصائح أخرى
يقول هذا ، ينبغي أن يكون على التوالي إلى الأمام
<اقتباس فقرة>[كما] دام لديها بيثون المحلي دعم SSL.
اقتباس فقرة>إذا كنت تستخدم فقط المصادقة الأساسية HTTP، يجب عليك تعيين معالج مختلفة، كما هو موضح هنا .
ونقلا المثال هناك:
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. جوجل للحصول على الثعبان + urllib2 + HTTP + الهضم.
وابتهاج،
والوثائق urllib2 لها مثالا في العمل مع المصادقة الأساسية: