当前位置: 首页>>代码示例>>Python>>正文


Python Browser.find_control方法代码示例

本文整理汇总了Python中mechanize.Browser.find_control方法的典型用法代码示例。如果您正苦于以下问题:Python Browser.find_control方法的具体用法?Python Browser.find_control怎么用?Python Browser.find_control使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mechanize.Browser的用法示例。


在下文中一共展示了Browser.find_control方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: backup_database

# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import find_control [as 别名]
def backup_database(url, username, password, database, destination):
    if not url.endswith("/"):
        url+="/"
    br = Browser()
    br.open(url)

    br.select_form(name="login_form")
    br["pma_username"] = username
    br["pma_password"] = password

    login_response = br.submit()

    resp = br.follow_link(url_regex=re.compile("^main\.php.*"))
    resp = br.follow_link(url_regex=re.compile("\./server_export\.php.*"))

    br.select_form(name="dump")
    # Select SQL export
    br.find_control(name="what").get(id="radio_plugin_sql").selected = True
    # Select database to export
    br.find_control(name="db_select[]").get(name=database).selected = True
    # Add SQL DROP statements to export
    br.find_control(name="sql_drop").get(id="checkbox_sql_drop").selected = True
    # Send as file
    br.find_control(name="asfile").get("sendit").selected = True

    # Compress file with bzip
    br.find_control(name="compression").get(id="radio_compression_bzip").selected = True

    ret = br.submit()
    open(destination, 'w').write(ret.read())
开发者ID:forsberg,项目名称:misctools,代码行数:32,代码来源:backup.py

示例2: test_login

# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import find_control [as 别名]
def test_login(login_url, studentid, username, password):
    #create a browser object
    br = Browser()
    #br.set_handle_redirect(False)

    br.set_handle_robots(False)
    br.addheaders = [(
        'User-agent', 'Mozilla/5.0 (Windows NT 5.2; '
        'WOW64) AppleWebKit/536.11 (KHTML, like Gecko) '
        ' Chrome/20.0.1132.47 Safari/536.11')]

    #open the login page
    br.open(login_url)
    br.select_form(nr=0)
    #read only?  try me.
    br.find_control("credentialsForm2_hf_0").readonly = False

    #whoa. via http://stackoverflow.com/a/1549036/561698
    br.form.new_control('text', 'username', {'value': ''})
    br.form.new_control('text', 'password', {'value': ''})
    br.form.fixup()
    br['username'] = username
    br['password'] = password

    outcome = None
    while True:
        try:
            br.submit()
            #print br.title()
            if br.title() == 'Fastt Math NG Stretch':
                outcome = 'PASSED'
            else:
                outcome = 'FAILED (no error)'
            break
        except HTTPError:
            #print "Got error code", e.code
            outcome = 'FAILED' + ' (u:' + username + '/p: ' + password + ')'
            break

    #return a dictionary with test results
    resp_dict = {
        'product': 'FASTT Math',
        'studentid': studentid,
        'tested_on': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'outcome': outcome
    }
    return resp_dict
开发者ID:TEAMSchools,项目名称:fastt_checks,代码行数:49,代码来源:check_fastt.py

示例3: yapistir

# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import find_control [as 别名]
def yapistir():
	br = Browser()
	br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0')]
	br.set_handle_robots(False)

	br.open("http://paste.ubuntu.com")
	br.select_form("pasteform")

	br['poster'] = coder
	br.find_control(name="syntax").value = ["python"]

	dosya_ac = open(dosya)
	kodlar = dosya_ac.read()
	br['content'] = kodlar
	br.submit()
	for link in br.links():
		k_link.append(link.url)
开发者ID:ExitStars,项目名称:PySted,代码行数:19,代码来源:pysted.py

示例4: str

# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import find_control [as 别名]
br.form.find_control("dummy3").readonly=False #så att vi kan manipulera värdena
br.form.find_control("dummy2").readonly=False
br.form.find_control("dummy1").readonly=False  


br.form["dummy1"]="3"
br.form["dummy2"]="filter"
br.form["dummy3"]= "akt"  #detta är för att bara få aktiva AB. De övriga två kontrollerna vet jag inte exakt vad de gör...
print br.form

print "nu är vi här"
response7 = br.submit() # 26 april: skumt, detta fungerar om jag inte tidigare preciserat vilket län jag vill söka i. Med länet utvalt får jag däremot noll träffar. Torde ha något att göra med vad br.form har för värden på sina olika attribut, men vad?

br.select_form(name="mainform")

dagens_org_nr = str(br.find_control("uss")) #här går vi "bakvägen" genom att extrahera strängen som innehåller samtliga org-nr för bolag med kunggörelser i dag.
#print br.form
dagens_org_nr=dagens_org_nr[30:-15] #en enda lång sträng med de orgnr som har kunggörelser i dag. Denna sträng stoppar vi tillbaka i formuläret lite längre ner.
print "dagens org_nr:"+dagens_org_nr
print "längd dagens org nr:" + str(len(dagens_org_nr))

print br
#print response7.read()

response8 = br.follow_link(text="F\xf6retag")
#print br

br.select_form(name="mainform")
print "mainform, rad 129"
print br.form
#br.form.find_control("limit").readonly = False #sätt till False så att vi kan ändra värdet
开发者ID:carriercomm,项目名称:scraperwiki-scraper-vault,代码行数:33,代码来源:styrelseandringar.py

示例5: print

# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import find_control [as 别名]
br.open(url)
br.select_form(nr=0)
br["login"] = args.username
br["password"] = args.password
if args.debug: print("Logging in . . .")
br.submit()
writeout("past_login", br)

if args.debug: print("Getting search page . . .")
br.open("https://hrsa.cunyfirst.cuny.edu/psc/cnyhcprd/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.CLASS_SEARCH.GBL")
writeout("on_search_form", br)

br.select_form(nr=0)

# How do I change this next semester?
mods = br.find_control('CLASS_SRCH_WRK2_STRM$45$')
item1 = Item(mods, {"contents": "1162", "value": "1162"})
item1.selected=True

mods = br.find_control('SSR_CLSRCH_WRK_SUBJECT_SRCH$0')
item2 = Item(mods, {"contents": args.subject, "value": args.subject})
item2.selected=True

# Next semester?
br['CLASS_SRCH_WRK2_STRM$45$']=['1162']
br['DERIVED_SSTSNAV_SSTS_MAIN_GOTO$155$']=['9999']
br['CLASS_SRCH_WRK2_INSTITUTION$42$']=[args.college + '01']
br['SSR_CLSRCH_WRK_SSR_EXACT_MATCH1$1']=['E']
br.form['SSR_CLSRCH_WRK_CATALOG_NBR$1']=args.klass
br['SSR_CLSRCH_WRK_SUBJECT_SRCH$0']=[args.subject]
writeout("without_ICAction", br)
开发者ID:guymatz,项目名称:cunyFirst,代码行数:33,代码来源:cunySearch.py

示例6: Bugzilla

# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import find_control [as 别名]

#.........这里部分代码省略.........
            return match.group('bug_id')

        match = re.search(
            '<div id="bugzilla-body">(?P<error_message>.+)<div id="footer">',
            response_html,
            re.DOTALL)
        error_message = "FAIL"
        if match:
            text_lines = BeautifulSoup(
                    match.group('error_message')).findAll(text=True)
            error_message = "\n" + '\n'.join(
                    ["  " + line.strip()
                     for line in text_lines if line.strip()])
        raise Exception("Bug not created: %s" % error_message)

    def create_bug(self,
                   bug_title,
                   bug_description,
                   component=None,
                   patch_file_object=None,
                   patch_description=None,
                   cc=None,
                   mark_for_review=False,
                   mark_for_commit_queue=False):
        self.authenticate()

        log('Creating bug with title "%s"' % bug_title)
        if self.dryrun:
            log(bug_description)
            return

        self.browser.open(self.bug_server_url + "enter_bug.cgi?product=WebKit")
        self.browser.select_form(name="Create")
        component_items = self.browser.find_control('component').items
        component_names = map(lambda item: item.name, component_items)
        if not component:
            component = "New Bugs"
        if component not in component_names:
            component = self.prompt_for_component(component_names)
        self.browser['component'] = [component]
        if cc:
            self.browser['cc'] = cc
        self.browser['short_desc'] = bug_title
        self.browser['comment'] = bug_description

        if patch_file_object:
            self._fill_attachment_form(
                    patch_description,
                    patch_file_object,
                    mark_for_review=mark_for_review,
                    mark_for_commit_queue=mark_for_commit_queue)

        response = self.browser.submit()

        bug_id = self._check_create_bug_response(response.read())
        log("Bug %s created." % bug_id)
        log("%sshow_bug.cgi?id=%s" % (self.bug_server_url, bug_id))
        return bug_id

    def _find_select_element_for_flag(self, flag_name):
        # FIXME: This will break if we ever re-order attachment flags
        if flag_name == "review":
            return self.browser.find_control(type='select', nr=0)
        if flag_name == "commit-queue":
            return self.browser.find_control(type='select', nr=1)
        raise Exception("Don't know how to find flag named \"%s\"" % flag_name)
开发者ID:flwh,项目名称:Alcatel_OT_985_kernel,代码行数:70,代码来源:bugzilla.py

示例7: __init__

# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import find_control [as 别名]

#.........这里部分代码省略.........
    def fetch_patches_from_commit_queue(self):
        patches_to_land = []
        for bug_id in self.fetch_bug_ids_from_commit_queue():
            patches = self.fetch_reviewed_patches_from_bug(bug_id)
            patches_to_land += patches
        return patches_to_land

    def authenticate(self):
        if self.authenticated:
            return

        if self.dryrun:
            log("Skipping log in for dry run...")
            self.authenticated = True
            return

        (username, password) = read_credentials()

        log("Logging in as %s..." % username)
        self.browser.open(self.bug_server_url + "index.cgi?GoAheadAndLogIn=1")
        self.browser.select_form(name="login")
        self.browser["Bugzilla_login"] = username
        self.browser["Bugzilla_password"] = password
        response = self.browser.submit()

        match = re.search("<title>(.+?)</title>", response.read())
        # If the resulting page has a title, and it contains the word "invalid" assume it's the login failure page.
        if match and re.search("Invalid", match.group(1), re.IGNORECASE):
            # FIXME: We could add the ability to try again on failure.
            error("Bugzilla login failed: %s" % match.group(1))

        self.authenticated = True

    def add_patch_to_bug(self, bug_id, patch_file_object, description, comment_text=None, mark_for_review=False):
        self.authenticate()

        log('Adding patch "%s" to bug %s' % (description, bug_id))
        if self.dryrun:
            log(comment_text)
            return

        self.browser.open(self.bug_server_url + "attachment.cgi?action=enter&bugid=" + bug_id)
        self.browser.select_form(name="entryform")
        self.browser["description"] = description
        self.browser["ispatch"] = ("1",)
        if comment_text:
            log(comment_text)
            self.browser["comment"] = comment_text
        self.browser["flag_type-1"] = ("?",) if mark_for_review else ("X",)
        self.browser.add_file(patch_file_object, "text/plain", "bug-%s-%s.patch" % (bug_id, timestamp()))
        self.browser.submit()

    def obsolete_attachment(self, attachment_id, comment_text=None):
        self.authenticate()

        log("Obsoleting attachment: %s" % attachment_id)
        if self.dryrun:
            log(comment_text)
            return

        self.browser.open(self.attachment_url_for_id(attachment_id, "edit"))
        self.browser.select_form(nr=1)
        self.browser.find_control("isobsolete").items[0].selected = True
        # Also clear any review flag (to remove it from review/commit queues)
        self.browser.find_control(type="select", nr=0).value = ("X",)
        if comment_text:
            log(comment_text)
            # Bugzilla has two textareas named 'comment', one is somehow hidden.  We want the first.
            self.browser.set_value(comment_text, name="comment", nr=0)
        self.browser.submit()

    def post_comment_to_bug(self, bug_id, comment_text):
        self.authenticate()

        log("Adding comment to bug %s" % bug_id)
        if self.dryrun:
            log(comment_text)
            return

        self.browser.open(self.bug_url_for_bug_id(bug_id))
        self.browser.select_form(name="changeform")
        self.browser["comment"] = comment_text
        self.browser.submit()

    def close_bug_as_fixed(self, bug_id, comment_text=None):
        self.authenticate()

        log("Closing bug %s as fixed" % bug_id)
        if self.dryrun:
            log(comment_text)
            return

        self.browser.open(self.bug_url_for_bug_id(bug_id))
        self.browser.select_form(name="changeform")
        if comment_text:
            log(comment_text)
            self.browser["comment"] = comment_text
        self.browser["bug_status"] = ["RESOLVED"]
        self.browser["resolution"] = ["FIXED"]
        self.browser.submit()
开发者ID:jackiekaon,项目名称:owb-mirror,代码行数:104,代码来源:bugzilla.py

示例8: __init__

# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import find_control [as 别名]
class RequestQuery:

    def __init__(self,config):
        self.br=Browser()

        self.config = config

        self.isLoggedIn = self.login2Savannah()

    def __del__(self):
        self.br.close()

    def closeRequest(self,task,msg):
        if self.isLoggedIn:
            self.createValueDicts()
            
            response = self.br.open('https://savannah.cern.ch/task/?'+str(task))

            html = response.read()

            self.br.select_form(name="item_form")

            control = self.br.find_control("status_id",type="select")
            control.value = [self.TicketStatusByLabelDict["Closed"]]

            #Put reason to the comment field
            control = self.br.find_control("comment",type="textarea")
            control.value = msg
                        
            #DBS Drop Down is a mandatory field, if set to None (for old requests), it is not possible to close the request
            self.setDBSDropDown()
                        
            self.br.submit()

            #remove JSON ticket
            self.removeJSONFile(task)
            
        return
                
    def createValueDicts(self):       
        if self.isLoggedIn:
            self.br.select_form(name="bug_form")
            
            control = self.br.find_control("custom_sb2",type="select")
            self.ReleaseByValueDict = self.getLabelByValueDict(control)

            control = self.br.find_control("custom_sb3",type="select")
            self.GroupByValueDict = self.getLabelByValueDict(control)

            control = self.br.find_control("custom_sb4",type="select")
            self.DBSByValueDict = self.getLabelByValueDict(control)
            self.DBSByLabelDict = self.getValueByLabelDict(control)

            control = self.br.find_control("resolution_id",type="select")
            self.StatusByValueDict = self.getLabelByValueDict(control)

            control = self.br.find_control("status_id",type="select")
            self.TicketStatusByLabelDict = self.getValueByLabelDict(control)

        return

    def setDBSDropDown(self):
        ## Get DBS URL by Drop Down
        control = self.br.find_control("custom_sb4",type="select")
        dbs_url = self.DBSByValueDict[control.value[0]]

        ## Get DBS URL by text field (for old entries)
        if dbs_url=='None':
            tmp = self.br.find_control("custom_tf4",type="text")
            dbs_url = tmp.value.replace(' ','')

            if dbs_url.find("analysis_02")!=-1:
                control.value = [self.DBSByLabelDict["cms_dbs_ph_analysis_02"]]
            elif dbs_url.find("analysis_01")!=-1:
                control.value = [self.DBSByLabelDict["cms_dbs_ph_analysis_01"]]
            elif dbs_url.find("local_09")!=-1:
                control.value = [self.DBSByLabelDict["cms_dbs_ph_prod_local_09"]]
            else:
                msg = 'DBS URL of the old request is neither analysis_01, analysis_02 nor local_09. Please, check!'
                logging.error(msg)
                raise RuntimeError, msg

        return
                
    def getLabelByValueDict(self, control):
        d = {}
        for item in control.items:
            value = item.attrs['value']
            label = item.attrs['label']
            d[value] = label
                
        return d

    def getRequests(self,**kargs):
        requests = []
        
        if self.isLoggedIn:
            self.selectQueryForm(**kargs)
            self.createValueDicts()
        
#.........这里部分代码省略.........
开发者ID:giffels,项目名称:PRODAGENT,代码行数:103,代码来源:RequestQuery.py

示例9: raw_input

# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import find_control [as 别名]
#.*?(\d+).*?(\d{4}-\d{2}-\d{2}\s*?[0-9:]+).*?([A-Z0-9]+).*?([A-Z0-9]+).*?([0-9.]+).*?(\d+).*?([A-Za-z0-9\+\-]+)

regex = re.compile('.*?(\d+).*?(\d{4}-\d{2}-\d{2}\s*?[0-9:]+).*?([A-Z0-9]+).*?([A-Z0-9]+).*?([0-9.]+).*?(\d+).*?([A-Za-z0-9\+\-]+)')

auth = False
while not auth:
	user = raw_input("Username: ")
	password = getpass.getpass()

	br = Browser()
	br.open(base_url)

	br.select_form(name='login')
	br['login_user'] = user
	br['password'] = password
	br.find_control(name="autologin").items[0].selected = True
	br.submit()

	for link in br.links():
		if link.text == 'my account':
			auth = True
			break
	if not auth:
		print "Authentication Failed"

print "Authenticated"

sublist = br.open(base_url+"status/"+user+"/signedlist")
sublist = sublist.read()

allsub = regex.findall(sublist)
开发者ID:DheerendraRathor,项目名称:Python-Snippets,代码行数:33,代码来源:spoj_download.py

示例10: fetch_isochrones

# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import find_control [as 别名]
def fetch_isochrones(isoc_kind='parsec_CAF09_v1.2S',
                     photsys_version='yang',
                     photsys_file='tab_mag_odfnew/tab_mag_ubvrijhk.dat',
                     kind_cspecmag='aringer09',
                     dust_sourceM='nodustM',
                     dust_sourceC='nodustC',
                     extinction_av='0.0',
                     imf_file='tab_imf/imf_chabrier_lognormal.dat',
                     sequence_type= 'single_isochrone',
                     isoc_age=False,
                     isoc_z =False,
                     isoc_z0=False,
                     isoc_z1=False,
                     isoc_dz=False,
                     isoc_lage0=False,
                     isoc_lage1=False,
                     isoc_dlage=False,
                     path='',
                     filename='Isochrone_teste.dat'):

    #Sequence_type = 'single_isochrone', 'sequence_constant_metallicity', 'sequence_constant_age'
    if sequence_type == 'single_isochrone' or sequence_type == 0: sequence_type = 0
    elif sequence_type == 'constant_metallicity' or sequence_type == 1 : sequence_type = 1
    elif sequence_type == 'constant_age' or sequence_type == 2: sequence_type = 2
    else: raise ValueError("Argument sequence_type must be in ('single_isochrone', 'constant_metallicity', "
                           "'constant_age')")

    warnings.simplefilter('always', UserWarning)

    #Handling bad values given for different sequence types
    if sequence_type == 0:
        if not isoc_age: raise ValueError("For sequence_type == 'single_isochrone', argument isoc_age must be provided")
        if not isoc_z: raise ValueError("For sequence_type == 'single_isochrone', argument isoc_z must be provided")
        if any((isoc_z0, isoc_z1, isoc_dz, isoc_lage0, isoc_lage1, isoc_dlage)):
            warnings.warn("For sequence_type == 'single_isochrone', arguments isoc_z0, isoc_z1, isoc_dz, isoc_lage0, isoc_lage1 and isoc_dlage are not used")

    elif sequence_type == 1:
        if not isoc_z: raise ValueError("For sequence_type == 'constant_metallicity', argument isoc_z must be provided")
        if not isoc_lage0: raise ValueError("For sequence_type == 'constant_metallicity', argument isoc_lage0 must be provided")
        if not isoc_lage1: raise ValueError("For sequence_type == 'constant_metallicity', argument isoc_lage1 must be provided")
        if not isoc_dlage: raise ValueError("For sequence_type == 'constant_metallicity', argument isoc_dlage must be provided")
        if any((isoc_age, isoc_z0, isoc_z1, isoc_dz)):
            warnings.warn("For sequence_type == 'constant_metallicity', arguments isoc_age, isoc_z0, isoc_z1, and isoc_dz are not used")

    elif sequence_type == 2:
        if not isoc_age: raise ValueError("For sequence_type == 'constant_age', argument isoc_age must be provided")
        if not isoc_z0: raise ValueError("For sequence_type == 'constant_age', argument isoc_z0 must be provided")
        if not isoc_z1: raise ValueError("For sequence_type == 'constant_age', argument isoc_z1 must be provided")
        if not isoc_dz: raise ValueError("For sequence_type == 'constant_age', argument isoc_dz must be provided")
        if any((isoc_z, isoc_lage0, isoc_lage1, isoc_dlage)):
            warnings.warn("For sequence_type == 'constant_age', arguments isoc_z, isoc_lage0, isoc_lage1, and isoc_dlage are not used")

    #Error raised when too many isochrones are requested
    if sequence_type == 1:
        N_isoc = len(np.arange(isoc_lage0, isoc_lage1, isoc_dlage))
        if N_isoc > 400:
            raise ValueError("you requested too many isochrones ({0}), maximum allowed is 400.\nTry to increase isoc_dlage or lower the difference between isoc_lage0 and isoc_lage1".fotmat(N_isoc))
    elif sequence_type == 2:
        N_isoc = len(np.arange(isoc_z0, isoc_z1, isoc_dz))
        if N_isoc > 400:
            raise ValueError("you requested too many isochrones ({0}), maximum allowed is 400.\nTry to increase isoc_dz or lower the difference between isoc_z0 and isoc_z1".format(N_isoc))

    #print 'Opening browser'
    br = Browser()
    br.open('http://stev.oapd.inaf.it/cgi-bin/cmd')
    br.select_form(nr = 0)

    #print 'Filling form'
    br.form['isoc_kind'] = [isoc_kind]
    br.form['photsys_version'] = [photsys_version]
    br.form['photsys_file'] = [photsys_file]
    br.form['kind_cspecmag'] = [kind_cspecmag]
    br.form['dust_sourceM'] = [dust_sourceM]
    br.form['dust_sourceC'] = [dust_sourceC]
    br.form['extinction_av'] = (extinction_av)
    br.form['imf_file'] = [imf_file]

    br.find_control("isoc_val").items[sequence_type].selected = True

    if sequence_type == 0:
        br.form['isoc_age'] = str(isoc_age)  # Isochrone age
        br.form['isoc_zeta'] = str(isoc_z)  # Isochrone metallicity

    elif sequence_type == 1:
        br.form['isoc_zeta0'] = str(isoc_z)  # Isochrone metallicity
        br.form['isoc_lage0'] = str(isoc_lage0)  # Isochrone log initial age
        br.form['isoc_lage1'] = str(isoc_lage1) # Isochrone log final age
        br.form['isoc_dlage'] = str(isoc_dlage)  # Isochrone log age step

    elif sequence_type == 2:
        br.form['isoc_age0'] = str(isoc_age)  # Isochrone age
        br.form['isoc_z0'] = str(isoc_z0)  # Isochrone initial metallicity
        br.form['isoc_z1'] = str(isoc_z1)  # Isochrone final metallicity
        br.form['isoc_dz'] = str(isoc_dz)  # Isochrone metallicity step

    #print('Submitting form')
    br.submit()

    #print('Downloading data')
    download_link = list(br.links())[0].absolute_url
#.........这里部分代码省略.........
开发者ID:felipefer42,项目名称:EITA,代码行数:103,代码来源:fetch_isochrones_v1_2.py

示例11: CoreEmulator

# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import find_control [as 别名]
class CoreEmulator(Emulator):

    def __init__(self, username, password):
        super(CoreEmulator, self).__init__(username, password)
        self.setup_emulator()

    def setup_emulator(self):
        self.browser = Browser()
        self.browser.set_handle_robots(False)
        self.browser.addheaders = moodle.USER_AGENT
        self.cookiejar = CookieJar()
        self.browser.set_cookiejar(self.cookiejar)

    def session_expired(self):
        return self.browser.geturl().endswith(moodle.LOGIN_LOCATION)

    @throws_moodlefuse_error(exception.LoginException)
    def login(self):
        self.open_login_page(self.browser.open)
        self.browser.select_form(
            predicate=lambda form: form.attrs.get('id') == attributes.LOGIN
        )
        self.browser.form.set_value(self.username, name='username')
        self.browser.form.set_value(self.password, name='password')
        resp = self.browser.submit()

        if resp.geturl().endswith(moodle.LOGIN_LOCATION):
            raise Exception

    @throws_moodlefuse_error(resource_errors.UnableToDownloadResource)
    def download(self, destination, source):
        source = str(source)
        if not source.startswith('http://') and not source.startswith('file://'):
            source = config['TEST_DATA'] + '/' + source

        self.browser.retrieve(source, destination)

    def open_link(self, url):
        response = self.browser.open(url)
        return BeautifulSoup(response.read())

    def check_form_checkbox(self, checkboxname):
        self.browser.find_control(checkboxname).items[0].selected = True

    def uncheck_form_checkbox(self, checkboxname):
        self.browser.find_control(checkboxname).items[0].selected = False

    def add_form_content(self, inputname, content):
        self.browser.form.set_value(content, name=inputname)

    def close_form(self):
        self.browser.submit()

    def set_form_to_first_form(self):
        self.browser.select_form(nr=0)

    def set_form_to_form_with_control_value(self, value):
        for form in self.browser.forms():
            for control in form.controls:
                if control.value == value:
                    self.browser.form = form

    @throws_moodlefuse_error(exception.UnableToToggleEditing)
    def turn_course_editing_on(self):
        self.set_form_to_form_with_control_value(moodle.EDIT_ON_MOODLE_BUTTON_TEXT)
        response = self.browser.submit()
        return BeautifulSoup(response.read())

    def _setup_assignments_for_parsing(self, submission_filter):
        self.set_form_to_form_with_control_value('Save and update table')
        self.browser.form["filter"] = [submission_filter]
        self.browser.form["perpage"] = ["100"]
        self.uncheck_form_checkbox('quickgrading')
        response = self.browser.submit()
        return BeautifulSoup(response.read())

    def filter_assignment_submissions(self):
        return self._setup_assignments_for_parsing("submitted")

    def unfilter_assignment_submissions(self):
        return self._setup_assignments_for_parsing("")

    @throws_moodlefuse_error(exception.UnableToToggleEditing)
    def turn_course_editing_off(self):
        self.set_form_to_form_with_control_value(moodle.EDIT_OFF_MOODLE_BUTTON_TEXT)
        response = self.browser.submit()
        return BeautifulSoup(response.read())

    @throws_moodlefuse_error(course_errors.InvalidMoodleIndex)
    def get_courses(self):
        return self.open_link(config['MOODLE_INDEX_ADDRESS'])

    @throws_moodlefuse_error(course_errors.UnableToObtainCategoryList)
    def get_course_categories(self, url):
        return self.open_link(url)

    @throws_moodlefuse_error(resource_errors.UnableToObtainResourceList)
    def get_course_resource_names(self, url):
        return self.open_link(url)

#.........这里部分代码省略.........
开发者ID:BroganD1993,项目名称:MoodleFUSE,代码行数:103,代码来源:core_emulator.py

示例12: __init__

# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import find_control [as 别名]

#.........这里部分代码省略.........
    def saveFile(self, url, dir=".", at_download=False):
        """Reads the response from a URL and saves it to a local
        file based on the name provided in the Content-Disposition
        header.  

	    The dir field specifies to the directory where the file will
        be stored.

        If the at_download flag is True then 'at_download/file' will
        be appended the URL.
        """
        if at_download:
            rsp = self.b.open(url_join(url,'at_download/file'))
        else:
            rsp = self.b.open(url)
 
        fname = get_filename(rsp)
	if fname:
            f = open('/'.join([dir, fname]), 'wb')
            f.write(rsp.read())
            f.close()

	return fname

    def putImageURL_old(self, imgfile, url, title=None, type='image/jpg'):
        sys.stderr.write('putImageURL %s to %s\n' % (imgfile,url))
        self.b.open('/'.join((url,'createObject?type_name=Image')))
        self.b.select_form("edit_form")
        if not title: title = path.basename(imgfile)
        self.b['title'] = title
        self.b.add_file(open(imgfile), type, path.basename(imgfile))
        try:
            # doesn't seem necessary but it is required for file upload
            form = self.b.find_control('image_delete')
            form.value = ["",]
            # print "This really does need to happen.."
        except:
            # print "That delete stuff never happens..." 
            pass
        self.b.submit("form.button.save")


    def putImageURL(self, filename, url, 
                   fileobj=None, title=None, type='image/jpg'):
        """Simple interface for uploading a file to a plone site.
           <URL> should be an existing folder on the site and
           <filename> should be a readable file.
        """ 

        #sys.stderr.write('putFileURL %s to %s\n' % (filename,url))
        if not title: title = path.basename(filename)
        if not fileobj: fileobj = open(filename, 'rb')

        self.b.open('/'.join((url,'createObject?type_name=Image')))
        self.b.select_form("edit_form")
        self.b['title'] = title
        self.b.add_file(fileobj, type, path.basename(filename))
        # form = self.b.find_control('file_delete')
        # form.value = ["",]

        self.b.submit("form.button.save")
        # r = self.b.open(self.b.click())
        # should check that it worked


    def putDocument(self, doc, url, title):
开发者ID:HelenRouty,项目名称:LEAM-reorganize,代码行数:70,代码来源:leamsite.py

示例13: exit

# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import find_control [as 别名]
	exit(0)

classtype = open('classcategory.txt', 'w')
class_type=[]

browser = Browser()
browser.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

# Cookie Jar
cj = cookielib.LWPCookieJar()
browser.set_cookiejar(cj)
browser.set_handle_robots(False)

browser.open("https://banner.uregina.ca/prod/sct/bwckschd.p_disp_dyn_sched") #to get semester specifics
browser.select_form(nr=0)
item = browser.find_control(id="term_input_id").get("%s" % semester)
item.selected = True

response = browser.submit()
content = response.read()

flag = 0

for line in StringIO.StringIO(content):
	if flag == 0:
		if '<SELECT NAME="sel_subj" SIZE="10" MULTIPLE ID="subj_id">' in line:
			flag = 1
	else:
		if '</SELECT>' not in line:
			x = line.split('"')
			try:
开发者ID:fengyuhan,项目名称:school-assignments,代码行数:33,代码来源:getClassBySemester.py

示例14: Browser

# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import find_control [as 别名]
# set up mechanize header
headers = [('User-Agent', 'Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1')]

# define target URL
url = "http://www.bseindia.com/getquote.htm"

br = Browser()

# browser parameters
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False) 

br.addheaders = headers

# make request
main_page = br.open(url)

# select the default form
br.select_form(nr=0)
br.find_control(id="suggestBoxEQ").value = "CAREERP"

# submit form
br.submit()
page_response = bs(br.response().read())

quote = page_response.find_all('div',{'class':'newsrheadingdiv'})
print quote
开发者ID:martiansideofthemoon,项目名称:stock-marker,代码行数:32,代码来源:get_quotes.py

示例15: print

# 需要导入模块: from mechanize import Browser [as 别名]
# 或者: from mechanize.Browser import find_control [as 别名]
cmssw2rank = {}
rank = 10

for release in release_list:
    cmssw2rank[release] = rank
    rank += 10

## Loop overall releases in Savannah and check if there are valid
## Hide deprecated versions
for links in br.links(text_regex="CMSSW_*_*"): 
    if links.text not in release_list:
        br.follow_link(links)
        print "Hide deprecated version %s" % links.text
        br.select_form(nr=1)
        control = br.find_control("status")
        control.value = ['H']
        br.submit()

## Doing a loop in all releases
## Create entry in Savannah for releases. If it already exist, update the rank
for release in release_list:
    try:
        #First, look if this CMSSW release is already there
        br.follow_link(text=release, nr=0)
        rank = cmssw2rank[release]
        print("Release %s already exists. Changing rank to %s" %(release,rank))
        br.select_form(nr=1)
        br['order_id']= str(rank)
        br['status']=['A']
        br.submit()
开发者ID:AlexVanSpilbeeck,项目名称:WmAgentScripts,代码行数:32,代码来源:StoreResultsAddCMSSWReleases.py


注:本文中的mechanize.Browser.find_control方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。