python的urllib2实现登录网页_使用urllib2登录到网站 – Python 2.7

我会先说这个,说我没有以这种方式登录一段时间,所以我可能会错过一些更多的“接受”的方法来做到这一点。

我不知道这是否是你的后来,但没有像机械化或更强大的框架像硒,在基本情况下,你只是看看表单本身和寻找输入的库。例如,查看www.reddit.com,然后查看渲染页面的源代码,您将找到以下表单:

class="login-form login-form-side">

remember me

reset password

login

这里我们看到一些输入的op,user,passwd和rem。此外,请注意action参数 – 即表单将被发布到的URL,因此将是我们的目标。所以现在最后一步是将参数打包到有效负载中,并将其作为POST请求发送到操作URL。在下面,我们创建一个新的开启者,添加处理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': '',

'passwd': ''

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值