[英]Login to website using urllib2 - Python 2.7
好吧,所以我將它用於reddit機器人,但我希望能夠弄清楚如何登錄任何網站。 如果這是有道理的....
我意識到不同的網站使用不同的登錄表單等。那么我如何找出如何為每個網站優化它? 我假設我需要在html文件中查找內容但不知道是什么。
我不想使用Mechanize或任何其他庫(這是所有其他答案都在這里,而不是實際上幫助我了解正在發生的事情),因為我想自己學習它究竟是如何工作的。
urllib2文檔真的沒有幫助我。
謝謝。
我會先說這個方法我已經有一段時間沒有用這種方式登錄了,所以我可能會錯過一些更“接受”的方法來做到這一點。
我不確定這是否是你所追求的,但沒有像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
- op
, user
, passwd
和rem
。 另外,請注意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
參數)。 再次,不確定這是否是你想要的,但希望它有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.