使用urllib2登录网站 - Python 2.7

时间:2012-12-18 03:51:05

标签: python python-2.7 login urllib2

好的,所以我将它用于reddit机器人,但我希望能够弄清楚如何登录任何网站。 如果这是有道理的......

我意识到不同的网站使用不同的登录表单等。那么我如何找出如何为每个网站优化它?我假设我需要在html文件中查找内容,但不知道是什么。

我不想使用Mechanize或任何其他库(这是所有其他答案都在这里,并没有真正帮助我了解正在发生的事情),因为我想自己学习它究竟是怎么回事所有的作品。

urllib2文档真的没有帮助我。

感谢。

1 个答案:

答案 0 :(得分:48)

我将在这方面说明我还没有以这种方式登录一段时间,所以我可能会错过一些更“接受”的方式来做这件事。

我不确定这是否是你所追求的,但没有像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参数)。再次,不确定这是否是你想要的,但希望它有所帮助。