栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用urllib2登录网站-Python 2.7

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用urllib2登录网站-Python 2.7

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

我不确定这是否是您要追求的,但是如果没有像这样的库

mechanize
或更强大的框架
selenium
,那么在基本情况下,您只需查看表单本身并查找即可
inputs
。例如,查看
www.reddit.com
,然后查看渲染页面的源,您将找到此表单:

<form method="post" action="https://ssl.reddit.com/post/login" id="login_login-main"  >    <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 ></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  href="/password">reset password</a>    </div>    <div >      <button  type="submit" tabindex="1">login</button>    </div>    <div ></div></form>

在这里,我们看到了几个

input
的- ,,和。另外,请注意参数-
即表单将发布到的URL,因此将成为我们的目标。因此,现在的最后一步是将参数打包到有效负载中,并将其作为请求发送到URL。同样在下面,我们创建了一个new
,添加了处理cookie和添加标头的功能,从而为我们提供了一个更强大的打开器来执行请求):
op``user``passwd``rem``action``POST``action``opener


import cookielibimport urllibimport urllib2# Store the cookies and create an opener that will hold themcj = cookielib.cookieJar()opener = urllib2.build_opener(urllib2.HTTPcookieProcessor(cj))# Add our headersopener.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 formauthentication_url = 'https://ssl.reddit.com/post/login'# Input parameters we are going to sendpayload = {  'op': 'login-main',  'user': '<username>',  'passwd': '<password>'  }# Use urllib to enpre the payloaddata = urllib.urlenpre(payload)# Build our Request object (supplying 'data' makes it a POST)req = urllib2.Request(authentication_url, data)# Make the request and read the responseresp = urllib2.urlopen(req)contents = resp.read()

请注意,这会变得更加复杂-
例如,您也可以使用GMail进行此操作,但是您需要提取每次都会更改的

GALX
参数(例如参数)。同样,不确定这是否是您想要的,但希望能有所帮助。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/574768.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号