如何使用python和机械化登录到网站 [英] how to login to a website with python and mechanize

查看:218
本文介绍了如何使用python和机械化登录到网站的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想登入 http://www.magickartenmarkt.de 网站,并在会员中进行分析,区域( https://www.magickartenmarkt.de/?mainPage=show Wants )。我看到了其他的例子,但我不明白为什么我的方法不工作。我确定了第一种方法的正确形式,但不清楚它是否有效。
在第二种方法中,Returing网页显示我没有访问成员区域。

i'm trying to log in to the website http://www.magickartenmarkt.de and do some analyzing in the member-area (https://www.magickartenmarkt.de/?mainPage=showWants). I saw other examples for this, but i don't get why my approaches didn't work. I identified the right forms for the first approach, but it's not clear if it worked. In the second approach the returing webpage shows me that i don't have access to the member area.

我很乐意为您提供帮助。

I would by glad for any help.

import urllib2
import cookielib
import urllib
import requests
import mechanize
from mechanize._opener import urlopen
from mechanize._form import ParseResponse

USERNAME = 'Test'
PASSWORD = 'bla123'
URL      = "http://www.magickartenmarkt.de"

# first approach
request = mechanize.Request(URL)
response = mechanize.urlopen(request)
forms = mechanize.ParseResponse(response, backwards_compat=False)
# I don't want to close?!
#response.close()

# Username and Password are stored in this form
form = forms[1]

form["username"] = USERNAME
form["userPassword"] = PASSWORD

#proof entering data has worked
user = form["username"]  # a string, NOT a Control instance
print user
pw = form["userPassword"]  # a string, NOT a Control instance
print pw
#is this the page where I will redirected after login?
print urlopen(form.click()).read () 

#second approach
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : USERNAME, 'userPassword': PASSWORD})

#login
response_web = opener.open(URL, login_data)

#did it work? for me not....
resp = opener.open('https://www.magickartenmarkt.de/?mainPage=showWants')
print resp.read()


推荐答案

为什么不使用浏览器实例来方便导航?机械化也有选择特定表单的能力(例如nr = 0将选择页面上的第一个表单)

Why not use a browser instance to facilitate navigation? Mechanize also has the ability to select particular forms (e.g. nr = 0 will select the first form on the page)

browser = mechanize.Browser()
browser.open(YOUR URL)
browser.select_form(nr = 0)
browser.form['username'] = USERNAME
browser.form['password'] = PASSWORD
browser.submit()

这篇关于如何使用python和机械化登录到网站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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