使用Python Mechanize自动登录表单时遇到问题

使用Python Mechanize自动登录表单时遇到问题,python,mechanize,Python,Mechanize,我一直在尝试自动化需要cookies的站点登录。我在这个网站上找到了答案,并回复了它,但我在登录时遇到了问题,因为我忘了我已经在这里有了一个帐户。我为我的双重帖子道歉,但我担心我的回复不会被看到 一个问题。当我试图复制它时,我遇到了一个错误 File "test5.py", line 6, in <module> self.br = mechanize.Browser( factory=mechanize.RobustFactory() ) NameError: name 'sel

我一直在尝试自动化需要cookies的站点登录。我在这个网站上找到了答案,并回复了它,但我在登录时遇到了问题,因为我忘了我已经在这里有了一个帐户。我为我的双重帖子道歉,但我担心我的回复不会被看到

一个问题。当我试图复制它时,我遇到了一个错误

File "test5.py", line 6, in <module>
self.br = mechanize.Browser( factory=mechanize.RobustFactory() )
NameError: name 'self' is not defined
对我来说,声明变量self似乎是个问题,但我对Python还不太熟悉,不知道是否是这样。 任何关于我为什么会犯这个错误的想法都将不胜感激

更新:: 通过删除self的所有实例,我能够克服最初的错误。现在,当我运行以下代码时,会出现以下错误:

    raise FormNotFoundError("no form matching "+description)
    mechanize._mechanize.FormNotFoundError: no form matching name 'Loginform'
代码如下:

!/usr/bin/python
import sys
import mechanize
import cookielib
from mechanize import ParseResponse, urlopen, urljoin, Browser
from time import sleep


class PrettifyHandler(mechanize.BaseHandler):
def http_response(self, request, response):
    if not hasattr(response, "seek"):
        response = mechanize.response_seek_wrapper(response)
    # only use BeautifulSoup if response is html
    if response.info().dict.has_key('content-type') and ('html' in     response.info().dict['content-type']):
        soup = MinimalSoup (response.get_data())
        response.set_data(soup.prettify())
    return response


br = mechanize.Browser( factory=mechanize.RobustFactory() )
br.add_handler(PrettifyHandler())
br.set_handle_robots(False)
cj = cookielib.LWPCookieJar()
cj.save('cookies.txt', ignore_discard=False, ignore_expires=False)
br.set_cookiejar(cj)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*  /*;q=0.8'),
                 ('User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0'),
                 ('Referer', 'https://****/admin/login.jsp'),
                 ('Accept-Encoding', 'gzip,deflate,sdch'),
                 ('Accept-Language', 'en-US,en;q=0.5'),
                 ]
br.open('https://****/admin/login.jsp')

print br.response

 # Select the first (index zero) form
br.select_form(name='Loginform') 
#br.select_form(nr=0)
 # User credentials
br.form['email'] = 'luskbo@gmail.com'
br.form['password'] = 'password!!!'
 # Login
br.submit()
# Inventory
 body = br.response().read().split('\n')

只要删除每个
self.
,它就会工作(如果没有任何其他错误)

self
通常仅用于从类中的方法中引用当前对象,而不是在模块级别

!/usr/bin/python
import sys
import mechanize
import cookielib
from mechanize import ParseResponse, urlopen, urljoin, Browser
from time import sleep


class PrettifyHandler(mechanize.BaseHandler):
def http_response(self, request, response):
    if not hasattr(response, "seek"):
        response = mechanize.response_seek_wrapper(response)
    # only use BeautifulSoup if response is html
    if response.info().dict.has_key('content-type') and ('html' in     response.info().dict['content-type']):
        soup = MinimalSoup (response.get_data())
        response.set_data(soup.prettify())
    return response


br = mechanize.Browser( factory=mechanize.RobustFactory() )
br.add_handler(PrettifyHandler())
br.set_handle_robots(False)
cj = cookielib.LWPCookieJar()
cj.save('cookies.txt', ignore_discard=False, ignore_expires=False)
br.set_cookiejar(cj)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*  /*;q=0.8'),
                 ('User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0'),
                 ('Referer', 'https://****/admin/login.jsp'),
                 ('Accept-Encoding', 'gzip,deflate,sdch'),
                 ('Accept-Language', 'en-US,en;q=0.5'),
                 ]
br.open('https://****/admin/login.jsp')

print br.response

 # Select the first (index zero) form
br.select_form(name='Loginform') 
#br.select_form(nr=0)
 # User credentials
br.form['email'] = 'luskbo@gmail.com'
br.form['password'] = 'password!!!'
 # Login
br.submit()
# Inventory
 body = br.response().read().split('\n')