2014-01-28 157 views
4

我正在學習如何使用python通過此site登錄網站,並將其應用到我的網站。這樣我就可以在沒有任何登錄要求的情況下打開網頁。它沒有顯示任何錯誤,但我無法完成我想要的。可能我的做法不是這樣做的方式,那麼請回答如何實現它。我想要的是通過我提供的憑據登錄,然後打開瀏覽器。但是當頁面加載時,它仍然沒有登錄。希望我的意思很清楚。請問我的問題是否未清除。將不勝感激。謝謝!使用python登錄網站並在瀏覽器中打開登錄網站

我修改一點點實現目標:

import urllib, urllib2, cookielib 
import webbrowser 
#cookie storage 
cj = cookielib.CookieJar() 
#create an opener 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
#Add useragent, sites don't like to interact programs. 
opener.addheaders.append(('User-agent', 'Mozilla/4.0')) 
opener.addheaders.append(('Referer', 'http://somesite.com/adminpanel/index.php')) 
#encode the login data. This will vary from site to site. 
#View the sites source code 
#Example############################################### 
#<form id='loginform' method='post' action='index.php'> 
#<div style="text-align: center;"> 
#Username<br /> 
#<input type='text' name='admin_userid' class='textbox' style='width:100px' /><br /> 
#Password<br /> 
#<input type='password' name='admin_password' class='textbox' style='width:100px' /><br /> 
#<input type='checkbox' name='remember_me' value='y' />Remember Me<br /><br /> 
#<input type='submit' name='login' value='Login' class='button' /><br /> 
login_data = urllib.urlencode({'admin_userid' : 'admin', 
           'admin_password' : 'test', 
           'login' : 'Login' 
           }) 
resp = opener.open('http://somesite.com/adminpanel/index.php', login_data) 
#you are now logged in and can access "members only" content. 
#when your all done be sure to close it 

webbrowser.open('http://somesite.com/adminpanel/index.php') 

resp.close() 
+0

你通過你的Python進行連接登錄腳本,而不是通過(新)連接你的瀏覽器打開... – Hyperboreus

+0

哦...是的。我現在看到它。謝謝。 – Robin

回答

0

通過這一點,你要打開的網址,但如果是餅乾嗎?我的意思是你缺少cookie,這就是你總是在瀏覽器上看到登錄頁面的原因。

webbrowser.open('http://somesite.com/adminpanel/index.php') 

你可以閱讀從RESP HTML和保存到一個html和,然後,如果你想上加載瀏覽器的HTML文件。

for html in resp: 
    print html 
+0

如果我保存html然後再次加載它,不會再要求認證嗎? – Robin

+0

如果顯示已保存的html,則它或多或少都是一個靜態頁面。所以它不會要求任何東西。我不知道你使用這個目的是爲了什麼目的。但最好的辦法是登錄後保存cookie(將cookie-jar指向文件)。下一次瀏覽頁面時,只需使用已保存的會話cookie(將文件指向cookie-jar),並且不會顯示您的登錄(直到cookie未過期)。 –