Python Forum

Full Version: local variable troubles
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,i was following a tutorial and typing my own code with jupyter notebook. and my problem is the code that i wrote has an error and the original(from the tutorial) code work well.
i checked and re-checked but i can't find any difference between the 2 code. can you help me to find the error

from bs4 import BeautifulSoup

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

import re
import time


class AmazonBot(object):
    global price
    
    def __init__(self,items):
        self.amazon_url = "https://www.amazon.ca/"
        self.items = items
        
        self.profile = webdriver.FirefoxProfile()
        self.options = Options()
        self.driver = webdriver.Firefox()
        ##self.driver = webdriver.Firefox(firefox_profile=self.profile, firefox_options=self.options)
        
        self.driver.get(self.amazon_url)
        
    def search_items(self)     :
        urls=[]
        prices=[]
        names=[]
        
        for item in self.items:
            print(f"Searching for {item}")
            
            self.driver.get(self.amazon_url)
            
            search_input = self.driver.find_element_by_id("twotabsearchtextbox")
            search_input.send_keys(item)
            
            time.sleep(2)
             
            search_button = self.driver.find_element_by_xpath('//*[@id="nav-search"]/form/div[2]/div/input')   
            search_button.click()
            
            time.sleep(2)
            
            first_result = self.driver.find_element_by_xpath("/html/body/div[1]/div[2]/div[1]/div[2]/div/span[3]/div[1]/div[1]")
            asin = first_result.get_attribute("data-asin")
            url = "https://www.amazon.ca/dp/" + asin
            price = self.get_product_price(url)
            name = self.get_product_name(url)
            
            
            
            prices.append(price)
            urls.append(url)
            names.append(name)
            
            
            print(price)
            print(name)
            print(url)
            
            time.sleep(2)
            
            
        return prices,urls,names     


    def get_product_price(self,url):
        self.driver.get(url)
         
        
        try:
            price = self.driver.get_element_by_id("priceblock_ourprice").text
        
        except:    
            pass
    
        try:
            price = self.driver.get_element_by_id("priceblock_dealprice").text
        
        except:    
            pass
    
        if price is None:
            price = "Note available"
        else:
            non_decimal = re.compile(r'[^\d.]+')
            price = non_decimal.sub('',price)
        
        return price    
    
    
    
    
    def get_product_name(self,url):
        self.driver.get(url)
        try:
            product_name= self.driver.get_element_by_id("productTitle")
        
        except:  
            pass
        
        if product_name is None:
                product_name = "Note available"
            
        return product_name
    
and that's the error
Error:
--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) <ipython-input-15-dc98a460d1f2> in <module> 2 amazon_bot = AmazonBot(items) 3 ----> 4 amazon_bot.search_items() <ipython-input-14-f083c7822166> in search_items(self) 50 asin = first_result.get_attribute("data-asin") 51 url = "https://www.amazon.ca/dp/" + asin ---> 52 price = self.get_product_price(url) 53 name = self.get_product_name(url) 54 <ipython-input-14-f083c7822166> in get_product_price(self, url) 86 pass 87 ---> 88 if price is None: 89 price = "Note available" 90 else: UnboundLocalError: local variable 'price' referenced before assignment
the original code is here the code link
There is two chances to define price as they are contained in two try/except blocks that pass on any exception.
        try:
            price = self.driver.get_element_by_id("priceblock_ourprice").text
         
        except:    
            pass
     
        try:
            price = self.driver.get_element_by_id("priceblock_dealprice").text
         
        except:    
            pass
if both of these raise an exception price wont be defined.
I would make the second pass in those try except blocks price = None.
but i wonder why in the original code (in link), it work perfectly ????
It's probably getting different data that didn't expose the problem Yoriz pointed out. You've changed quite a bit of the code. So you are getting different data, and your data doesn't have the elements that the try/except blocks are looking for.