如何登录一个网站,Python和机械化(How to login to a website with

2019-09-03 21:10发布

我试图登录到网站http://www.magickartenmarkt.de ,并做一些分析在会员区( https://www.magickartenmarkt.de/?mainPage=showWants )。 我看到这个其他的例子,但我不明白为什么我的做法没有奏效。 我确定了第一种方法的正确形式,但如果它的工作目前还不清楚。 在第二种方法的returing网页让我发现,我没有进入会员区。

我会用高兴的任何帮助。

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()

Answer 1:

为什么不使用浏览器实例,以方便导航? 机械化还具有选择特定形式的能力(例如,NR = 0将选择页面上的第一种形式)

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


Answer 2:

网络自动化? 绝对“WEBBOT”

webbot作品甚至与动态变化的ID和类名的网页,并具有比硒更多的方法和特点。

这里有一个片段:)

from webbot import Browser 
web = Browser()
web.go_to('google.com') 
web.click('Sign in')
web.type('mymail@gmail.com' , into='Email')
web.click('NEXT' , tag='span')
web.type('mypassword' , into='Password' , id='passwordFieldId') # specific selection
web.click('NEXT' , tag='span') # you are logged in ^_^


文章来源: How to login to a website with python and mechanize