Python:在网站上登录 [英] Python: Login on a website

查看:86
本文介绍了Python:在网站上登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图登录一个网站并进行自动清理工作.

I trying to login on a website and do automated clean-up jobs.

我需要登录的站点是: http://site.com/Account/LogOn

The site where I need to login is : http://site.com/Account/LogOn

我尝试了各种在Stack上找到的代码,例如使用python登录到网站(但我停留在这行上

I tried various codes that I found it on Stack, like Login to website using python (but Im stuck on this line

session = requests.session(config={'verbose': sys.stderr}) 

我的JetBeans不喜欢'verbose'告诉我我需要做点什么,但没有确切说明.)

where my JetBeans doesnt like 'verbose' telling me that i need to do something, but doesnt explain exactly what).

我也尝试过这样的方法:浏览器仿真-Python ,但是也没有运气.

I also tried this: Browser simulation - Python, but no luck with this too.

有人可以帮助我吗?所有的答案将不胜感激.预先感谢.

Can anyone help me? All answers will be appreciate. Thanks in advance.

PS:我2周前开始学习Python,因此请详细说明我对理解"水平的了解:)

PS: I started learning Python 2 weeks ago so please elaborate your answer for my "pro" level of undersanding :)

-------------------------更新:-------------------- ---------

-------------------------UPDATE:-----------------------------

我设法登录,但是当我尝试在其他页面上移动并按一个按钮时,它显示请登录!".

I manage to login, but when I'm trying to move on other page and push a button, it says Please Log in!

我使用以下代码:

url = 'http://site.com/Account/LogOn'
values = {'UserName': 'user',
          'Password': 'pass'}

data = urllib.urlencode(values)
cookies = cookielib.CookieJar()

opener = urllib2.build_opener(
    urllib2.HTTPRedirectHandler(),
    urllib2.HTTPHandler(debuglevel=0),
    urllib2.HTTPSHandler(debuglevel=0),
    urllib2.HTTPCookieProcessor(cookies))

response = opener.open(url, data)
the_page = response.read()
http_headers = response.info()
print response

登录后,我需要设置一个菜单值,该值在HTML中如下所示:

After I log in I need to swith a menu value, that looks like this in HTML:

<select id="menu_uid" name="menu_uid" onchange="swapTool()" style="font-size:8pt;width:120px;">
<option value="1" selected>MyProfile</option>
...
<option value="6" >DeleteTree</option>

,但是如果我形成这样的URL,我也可以直接做到: http://site.com/Account/management.html?Category = 6& deltreeid = 6& do =删除+树

but I also can do it directly if I form a URL like this: http://site.com/Account/management.html?Category=6&deltreeid=6&do=Delete+Tree

那么,如何构建此URL并提交它?再次感谢!

So , how can I build this URL and submit it? Thanks again!

推荐答案

省去很多麻烦,并使用 requests :

Save yourself a lot of headache and use requests:

url = 'http://site.com/Account/LogOn'
values = {'UserName': 'user',
          'Password': 'pass'}

r = requests.post(url, data=values)
# Now you have logged in

params = {'Category': 6, 'deltreeid': 6, 'do': 'Delete Tree'}
url = 'http://site.com/Account/management.html'

# sending cookies as well
result = requests.get(url, data=params, cookies=r.cookies)

这篇关于Python:在网站上登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆