【发布时间】:2021-01-09 05:28:08
【问题描述】:
我是 stackoverflow 社区的新手,一般来说也是编程新手。我的第一个项目是构建一个网络爬虫,看看我是否可以收集市场数据。在尝试构建它时,我一直陷入未绑定的本地错误。我知道这与我如何实例化我的类以及我如何引用变量有关,strong text 但不知道如何解决它..
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
【问题讨论】:
标签: python class web-scraping