错误局部变量在赋值前已被引用 [英] Error local variable has been referenced before assignment

查看:74
本文介绍了错误局部变量在赋值前已被引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 stackoverflow 社区的新手,也是一般编程的新手.我的第一个项目是构建一个网络爬虫,看看我是否可以收集市场数据.在尝试构建它时,我一直被未绑定的本地错误卡住.我知道这与我如何实例化我的类以及我如何引用变量有关,强文本但不知道如何解决它..

I am new to the stackoverflow community, and new to programming in general. One of my first projects is to build a web scraper to see if I can collect market data. In attempting to build this, I keep getting stuck with an unbound local error. I am aware that this has something to do with how I am instantiating my class and how I am referencing the variable,strong text but not sure how to trouble shoot it..

class Stock:
    def __init__(self,symbol,company):
        self.symbol = symbol
        self.company = company
        self.data = []
            
            
    
    def query_stock_symbol(self):
        wait_time = round(max(5, 10 +random.gauss(0,3)), 2)
        time.sleep(wait_time)
        
        
        url = 'https://www.barrons.com/quote/stock/us/xnys/%s?mod=DNH_S'  % (self.symbol)
        page = requests.get(url)
        if page.status_code == 403 or page.status_code == 404:
            url = 'https://www.barrons.com/quote/stock/us/xnas/%s?mod=DNH_S' % (self.symbol)
       
        user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
        headers = {'User-Agent': user_agent}
        req = urllib.request.Request(url,headers=headers)
        
        try:
            response = urllib.request.urlopen(req)
        except urllib.error.URLError as e:
            print(e.reason)
           
        self.soup = BeautifulSoup(response, 'html.parser')
           
        
#         Finding stock price
        for a in self.soup.findAll('span',{'class':'market_price'}):
            stock_price_str = a.text.replace(',','')
            if stock_price_str != 'N/A':
                self.stock_price = float(stock_price_str)
            else:
                self.stock_price = None

我收到的错误是这样的

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-277-f9c756bf109f> in <module>
      1 x = Stock('CRM','Salesforce')
----> 2 x.query_stock_symbol()
      3 

<ipython-input-276-1f910b91d713> in query_stock_symbol(self)
     26             print(e.reason)
     27 
---> 28         self.soup = BeautifulSoup(response, 'html.parser')
     29 
     30 

UnboundLocalError: local variable 'response' referenced before assignment
```


Thanks for all your time and consideration, I really do appreciate it

推荐答案

那是因为当您尝试使用它时,您在 try 块中声明了 response 在该块之外,您可以:

That is because you have response declared in a try block while you attempt to use it outside of that block, you could either:

1- 在 try 块中使用它之前全局声明 response,如下所示:

1- declare response globally before using it inside the try block, like this:

try:
    global response
    response = ...
except ...:
    ...
self.soup = ....

2- 像这样在 response 赋值下面的 try 块中实例化 Soup 对象:

2- instantiate the Soup object inside the try block below the response assignment like this:

try:
    response = ...
    self.soup = BeautifulSoup(response, 'html.parser')

3- 在 try 块之前声明 response 变量,这是一种更有问题的方法,并且可能会在响应未正确分配时导致问题(例如 exception 被引发),但是如果你决定这样做,你可以做这样的事情:

3- declare the response variable before the try block, this is a more problematic approach and could lead to problems when response is not assigned correctly (like when the exception is raised), however if you decide to go with this, you could do something like this:

response = None
try:
    response = ...
except ...:
    .....
self.soup = ...

永远记住本地声明的变量,比如在try块、if块、else块等在所述块之外不可访问,它们是该块本地

Always remember that locally declared variables, like in a try block, an if block, an else block, etc. are not accessible outside of said block, they are local to that block

这篇关于错误局部变量在赋值前已被引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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