2012-12-18 128 views
33

好的,所以我用這個來作爲reddit機器人,但我想能夠弄清楚如何登錄到任何網站。 如果這是有道理的......使用urllib2登錄到網站 - Python 2.7

我意識到,不同的網站使用不同的登錄表單等等。那麼我怎麼知道如何優化它爲每個網站?我假設我需要在html文件中查找某些內容,但不知道是什麼。

我不想使用機械化或任何其他庫(這是所有其他答案都在這裏,並沒有真正幫助我瞭解發生了什麼),因爲我想自己學習究竟如何它一切正常。

urllib2文檔確實沒有幫助我。

謝謝。

回答

45

我會在前言中說我還沒有用這種方式登錄過一段時間,所以我可能會錯過一些更「接受」的方式來做到這一點。

我不知道這是否是你追求的,但沒有像mechanize庫或類似selenium一個更強有力的框架,在基本情況下,你只要看看錶單本身並尋求出inputs。舉例來說,看着www.reddit.com,然後查看所呈現的頁面的源代碼,你會發現這種形式:

<form method="post" action="https://ssl.reddit.com/post/login" id="login_login-main" 
    class="login-form login-form-side"> 
    <input type="hidden" name="op" value="login-main" /> 
    <input name="user" placeholder="username" type="text" maxlength="20" tabindex="1" /> 
    <input name="passwd" placeholder="password" type="password" tabindex="1" /> 

    <div class="status"></div> 

    <div id="remember-me"> 
     <input type="checkbox" name="rem" id="rem-login-main" tabindex="1" /> 
     <label for="rem-login-main">remember me</label> 
     <a class="recover-password" href="/password">reset password</a> 
    </div> 

    <div class="submit"> 
     <button class="btn" type="submit" tabindex="1">login</button> 
    </div> 

    <div class="clear"></div> 
</form> 

這裏,我們看到了幾個input的 - opuserpasswdrem。此外,請注意action參數 - 即表單將發佈到的URL,因此將成爲我們的目標。所以現在最後一步是將這些參數打包成一個有效載荷,並將其作爲POST請求發送到action URL。另外下面,我們創建了一個新的opener,增加處理cookie,並添加標題爲好,給我們一個稍微強大的揭幕戰執行請求)的能力:

import cookielib 
import urllib 
import urllib2 


# Store the cookies and create an opener that will hold them 
cj = cookielib.CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 

# Add our headers 
opener.addheaders = [('User-agent', 'RedditTesting')] 

# Install our opener (note that this changes the global opener to the one 
# we just made, but you can also just call opener.open() if you want) 
urllib2.install_opener(opener) 

# The action/ target from the form 
authentication_url = 'https://ssl.reddit.com/post/login' 

# Input parameters we are going to send 
payload = { 
    'op': 'login-main', 
    'user': '<username>', 
    'passwd': '<password>' 
    } 

# Use urllib to encode the payload 
data = urllib.urlencode(payload) 

# Build our Request object (supplying 'data' makes it a POST) 
req = urllib2.Request(authentication_url, data) 

# Make the request and read the response 
resp = urllib2.urlopen(req) 
contents = resp.read() 

注意,這可以得到更爲複雜 - 例如,您也可以使用GMail執行此操作,但您需要提取每次都會更改的參數(例如參數GALX)。再次,不知道這是你想要的,但希望它有幫助。

+0

這是/令人驚歎/,謝謝! 幾乎正是我想要的,現在我知道我還需要閱讀更多的內容。完善! – tommo

+1

@tommo沒問題我的朋友 - 我記得當我嘗試將那些東西排除在外時,經歷了完全相同的問題線:)祝你好運! – RocketDonkey

+0

謝謝隊友:)我其實還有一個問題,我找不到答案,如果你不介意回答 - 爲什麼你在[[('User-agent'中使用[()]括號, 'RedditTesting')]「? 在文檔中只有正常的括號。 – tommo