使用urllib2登录网站 - Python 2.7

tom*_*mmo 36 python login urllib2 python-2.7

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

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

我不想使用Mechanize或任何其他库(这是所有其他答案都在这里,而不是实际上帮助我了解正在发生的事情),因为我想自己学习它究竟是如何工作的.

urllib2文档真的没有帮助我.

谢谢.

Roc*_*key 50

我会先说这个方法我已经有一段时间没有用这种方式登录,所以我可能会错过一些更"接受"的方法来做到这一点.

我不确定这是不是你所追求的,但没有类似的库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>
Run Code Online (Sandbox Code Playgroud)

在这里,我们看到了几个input的- ,,op 和.另外,请注意参数 - 即表单将发布到的URL,因此将成为我们的目标.所以现在最后一步是将参数打包到有效负载中并将其作为请求发送到URL.下面,我们创建一个新的,添加处理cookie和添加标题的能力,为我们提供一个更强大的开启者来执行请求):userpasswdremactionPOSTactionopener

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()
Run Code Online (Sandbox Code Playgroud)

请注意,这可能会变得更加复杂 - 例如,您也可以使用GMail执行此操作,但您需要提取每次都会更改的GALX参数(例如参数).再次,不确定这是否是你想要的,但希望它有所帮助.

  • 第二个帮助很大,但是当我导航到有关登录的其他页面时,它的行为就像我没有登录。有人知道如何解决此问题吗?我正在使用urllib和美丽的汤进行网络解析。 (2认同)