使用urllib2login到网站 – Python 2.7

好的,所以我使用这个作为一个reddit机器人,但我想能够弄清楚如何login到任何网站。 如果这是有道理的….

我意识到不同的网站使用不同的login表单等,那么我怎么知道如何优化每个网站? 我假设我需要寻找的东西在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> 

在这里,我们看到一些inputopuserpasswdrem 。 另外,请注意action参数 – 表单将被发布到的URL,因此将成为我们的目标。 所以现在最后一步是将这些参数打包成一个有效负载,并将其作为POST请求发送到action URL。 同样在下面,我们创build一个新的opener ,添加处理cookies和添加标头的能力,给我们一个稍微更强大的开启者来执行请求):

 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参数)。 再次,不知道这是你想要的,但希望它有帮助。