您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用urllib2登录网站-Python 2.7

使用urllib2登录网站-Python 2.7

首先,我会说我一段时间没有以这种方式登录,因此我可能会错过一些更“被接受”的方式来进行登录

我不确定这是否是您要追求的,但是如果没有像这样的库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="check@R_495_2419@" 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的- ,,和。另外,请注意参数- 即表单将发布到的URL,因此将成为我们的目标。因此,现在的最后一步是将参数打包到有效负载中,并将其作为请求发送到URL。同样在下面,我们创建了一个new ,添加了处理cookie和添加标头的功能,从而为我们提供了一个更强大的打开器来执行请求):op``user``passwd``rem``action``POST``action``opener

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参数(例如参数)。同样,不确定这是否是您想要的,但希望能有所帮助。

python 2022/1/1 18:50:07 有343人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶