简体   繁体   English

使用Python和Mechanize登录网站

[英]Login to a website using Python and Mechanize

I'm trying to login to portfolio123.com using Mechanize. 我试图登录到portfolio123.com使用机械化。 For some reason I am not getting the LoginPassword field. 由于某种原因,我没有得到LoginPassword字段。

Here is the code so far: 这是到目前为止的代码:

import mechanize

br = mechanize.Browser()
br.select_form(nr=0)
br['LoginUsername'] = user_name 
br['LoginPassword'] = password # This line does not work yet. 

The last line does not work. 最后一行不起作用。 The control is not found. 找不到控件。 We can confirm this by running the following code: 我们可以通过运行以下代码来确认这一点:

br.form = list(br.forms())[0]
for control in br.form.controls:
    print "type=%s, name=%s value=%s" % (control.type, control.name, br[control.name])

returns: 收益:

type=text, name=LoginUsername value=xxxxx
type=submit, name=Login value=Login
type=hidden, name=url value=index.jsp

But when I open the url in a browser the pasword field is there. 但是,当我在浏览器中打开URL时,密码字段存在了。 So how do I get to it? 那么我该怎么做呢?

It is not quite clear why Mechanize doesn't see the LoginPassword field. 尚不清楚Mechanize为什么看不到LoginPassword字段。 I've tried multiple things: set a User-Agent , tried prettifying the response with BeautifulSoup thinking about HTML-parsing problems, tried to modify the password input attributes on the fly etc. 我已经尝试了多种方法:设置User-Agent ,尝试使用BeautifulSoup考虑HTML解析问题来美化响应 ,尝试动态修改密码输入属性等。

As a workaround, robobrowser can handle the login form without any problems: 解决方法是, robobrowser可以处理登录表单而不会出现任何问题:

import robobrowser

url = "https://www.portfolio123.com/login.jsp"
browser = robobrowser.RoboBrowser()
browser.open(url)

form = browser.get_form()
form['LoginUsername'] = 'Username'
form['LoginPassword'] = 'Password'
browser.submit_form(form)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM