从函数中索引全局字典

时间:2014-07-02 16:54:47

标签: python debugging dictionary global-variables

我在函数中引用全局字典中的元素时遇到了一些麻烦;字典存储页面的URL以最小化对多个变量声明的需要。

这是我的代码:

import requests

page = {
'index':'http://www.exampleurl.co.uk/index.php',
'login':'http://www.exampleurl.co.uk/login.php',
'find':'http://www.exampleurl.co.uk/find.php',
'portfolio':'http://www.exampleurl.co.uk/portfolio.php'
}

def login():    
    with requests.Session() as c:

        c.get(page['login'])

        login_data = dict(email = USERNAME, password = PASSWORD, submit = 'Login', cookie = 'yes')
        c.post(url, data = login_data, headers = {'Referer': page['index']})
        page = c.get(page['portfolio'])

        print page.content

login()函数之前已经过测试,希望不会出现问题。

错误如下:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    login()
  File "C:\Users\__\Desktop\__\script.py", line 22, in login
    c.get(page['login'])
UnboundLocalError: local variable 'page' referenced before assignment

欢迎任何建议

1 个答案:

答案 0 :(得分:0)

只需更改收件人姓名:

def login():    
    with requests.Session() as c:

        c.get(page['login'])

        login_data = dict(email = USERNAME, password = PASSWORD, submit = 'Login', cookie = 'yes')
        c.post(url, data = login_data, headers = {'Referer': page['index']})
        # this is the offending line
        page_ret = c.get(page['portfolio'])

        print page_ret.content