def main(): get_total = [] total = 0 p1 = product.Product() p1.set_product_name("Apples") p1.set_product_price(4.79) get_total.append(p1.get_product_price()) print(p1) p2 = product.Product() p2.set_product_name("Pizza") p2.set_product_price(5.99) get_total.append(p2.get_product_price()) print(p2) p3 = product.Product() p3.set_product_name("Hummus") p3.set_product_price(5.79) get_total.append(p3.get_product_price()) print(p3) for price in get_total: total += price print("Grand Total the customer needs to pay is: {}".format(total))
def test_getValue(self): prod = product.Product('test', 1, 5.0) self.assertEqual(prod.getValue(), 5.0) prod = product.Product('nazwaProduktu', 3, 2.0) self.assertEqual(prod.getValue(), 6) prod = product.Product('nazwaProduktu 321', 5, 10) self.assertEqual(prod.getValue(), 50)
def test_PrintBasket(self): basket = [] item = product.Product("CH1", 1, '', 3.11, 0) basket.append(item) item = product.Product("CF1", 1, 'BOGO', 11.23, -11.23) basket.append(item) item = product.Product("CF1", 2, '', 11.23, 0) basket.append(item) with unittest.mock.patch.object(setup, "GetBasket", return_value = basket): total = checkout.PrintBasket() self.assertEqual(total,14.34)
def _data_to_product(self, list): ''' Take a list of dict (product data), checks arguments and returns a list of Product instances. ''' return [product.Product(data) for data in list if self._validate_data(data)]
async def __bestbuy(product, content): soup = BeautifulSoup(content, "lxml") error_message = None price = None try: if soup.find( "button", class_="btn btn-disabled btn-lg btn-block add-to-cart-button" ) is not None: error_message = "product unavailable" price = None else: price = soup.find( "div", class_="priceView-hero-price priceView-customer-price" ).findChild("span", attrs={"aria-hidden": "true"}) price = float( re.search("[0-9]+\.*[0-9]*", price.text.replace(',', ".")).group(0)) except Exception as e: price = None error_message = e finally: return p.Product(product.get_name(), price, product.get_url(), product.get_price_alert(), product.get_currency(), error_message)
async def __amazon(product, content): soup = BeautifulSoup(content, "lxml") error_message = None price = None try: if soup.find("div", id="availability", class_="a-section a-spacing-base").findChild( "span", class_="a-size-medium a-color-success") is None: error_message = "product unavailable" price = None else: price = soup.find( "span", id="priceblock_ourprice", class_= "a-size-medium a-color-price priceBlockBuyingPriceString") price = float( re.search("[0-9]+\.*[0-9]*", price.text.replace(',', ".")).group(0)) except Exception as e: price = None error_message = e finally: return p.Product(product.get_name(), price, product.get_url(), product.get_price_alert(), product.get_currency(), error_message)
def addUniqueProduct(self, productID, unitSize: float, UOM: str, brandType: str, desc: str, periodID: int, outletID: int, unitCount: float, sales: float): """ Method: void addUniqueProduct ( T productID, float unitSize, string UOM, string desc, int periodID, int outletID, float unitCount, float sales ) Description: This method checks whether a Product object with the given product ID already exists. If not, it creates a new Product object. Otherwise, it aggregates the given properties with those of the existing object. Arguments: T productID: Unique identifier of the product to be added. float unitSize: Volume or mass of a single unit of product. string UOM: Unit of measure. string desc: Concatenated text features of the product. int periodID: Unique identifier of the reference period during which the product was sold. int outletID: Unique identifier of the outlet at which the product was sold. float unitCount: Number of units sold. """ if productID not in self.products: self.products[productID] = pro.Product(productID, UOM, brandType, desc) self.products[productID].addProperties(periodID, outletID, unitSize, unitCount, sales)
async def __walmart(product, content): soup = BeautifulSoup(content, "lxml") error_message = None price = None try: x = soup.find( "div", class_="prod-ProductOffer-oosMsg prod-PaddingTop--xxs") if x is not None: error_message = "product unavailable" price = None else: a = soup.find("span", class_="price-characteristic", attrs={"itemprop": "price"}) if a is None: error_message = "can't get price!" price = None else: price = float(a["content"]) except Exception as e: price = None error_message = e finally: return p.Product(product.get_name(), price, product.get_url(), product.get_price_alert(), product.get_currency(), error_message)
def __init__(self, env): # Create POM objects: self.homepage = homepage.Homepage(env) # self.faq = faq.Faq(self) # self.contact = contact.Contact(self) self.product = product.Product(env) self.products = products.Products(env) self.cart = cart.Cart(env)
def add_product(self, new_product, new_product_price, new_product_category): new_product_id = random.randrange(100000, 999999, 1) self.products[new_product + str(new_product_id)] = product.Product( new_product, new_product_price, new_product_category, new_product_id) print(f"Stocked {new_product} ID:{new_product_id}") return self
def main(filepath, folderpath): # Tries to open the file for links extraction try: links_file = open(filepath, 'r') except Exception as e: print(e) # Display error msg exit() # Separate links into a link list links = [ link for link in links_file.read().split('\n') if link != '' and link[0] != '#' ] # Check if the file isn't empty if (len(links) == 0): print("ERROR: No links found on the file!") exit() # Create Product list global products products = [pd.Product(link) for link in links] for i in range(len(products)): if THREAD_ENABLE: CreateThread().start() else: fetchNext() # Wait until all threads are done while threading.active_count() != 1: continue # Sort data by price global sorted_data total_sum = 0 for item, price in sorted(data.items(), key=lambda x: x[1], reverse=True): total_sum += price no_occur = repeatData[item] if item in repeatData else 1 itemName = "({}x) - {}".format(no_occur, item) sorted_data[itemName] = price print("R$ {:8.2f}\t({}x) {}".format(price, no_occur, item[0:70])) total_sum = round(total_sum, 2) sorted_data['TOTAL'] = total_sum print('-' * 86) print("R$ {:8.2f}\t{}".format(total_sum, 'TOTAL')) print('-' * 90) output_filepath = folderpath + ("/" if folderpath[-1] != '/' else "") + \ filepath.split('.')[0].split("/")[-1] print("Output filepath: {}".format(output_filepath)) logs.write2json(output_filepath, sorted_data)
def _get_product_by_id(self, id): ''' Get product of given id from 'product' table. Return a Product object. ''' self.cursor = self.mydb.cursor(dictionary=True) query = f'SELECT * FROM PRODUCT WHERE id = {id};' self.cursor.execute(query) for row in self.cursor: prod = product.Product(row) return prod
def generate_csv(data): # headers = OrderedDict([("c1", None), ("c2", None), ("c3", None), ("c4", None)]) headers = OrderedDict(product.Product().__dict__) csv_file_name = generate_csv_name() print("\nGenerating CSV File: {}".format(csv_file_name)) with open(csv_file_name, "w", newline="", encoding="utf-8") as fobj: dw = csv.DictWriter(fobj, delimiter=",", fieldnames=headers) dw.writeheader() for row in data: dw.writerow(row) return None
def from_csv(cls, lines, **opts): self = cls() invdicts = parse_csv(lines, select=['name', 'quant', 'price'], types=[str, int, float], **opts) for p in invdicts: self.append(product.Product(**p)) return self
def get_products_from_category(self, category): ''' Return a list of all Products from the given category. ''' self.cursor = self.mydb.cursor(dictionary=True) query = f"SELECT * FROM product WHERE cat_id ={category.id}" products_list = [] self.cursor.execute(query) for row in self.cursor: row['category'] = category.name products_list.append(product.Product(row)) return products_list
def parse_products(product_document): products_list = [] jdsports_soup = bs4.BeautifulSoup(product_document,"lxml") products_soup = jdsports_soup.find_all("li",{"class":"productListItem"}) for product_soup in products_soup: cont = (product_soup.find("a",{"data-e2e":"product-listing-name"})) url = cont.attrs["href"] image = (product_soup.find("img").attrs["src"]) price = (product_soup.find("span",{"data-e2e":"product-listing-price"})).get_text().replace("Â","") title = cont.get_text() pid = re.search("/([0-9]+)/",url).groups()[0] url = "https://jdsports.co.uk"+url products_list.append(prd.Product(title,url,pid,price,image,"jdsports.co.uk")) products_list = products_list[:config.ppr] return products_list[::-1]
def unpack(self, products_file): data = open(products_file).readlines() inventory = [] for d in data: current = d.rstrip("\n").split(",") # Constructor argments name = current[0] description = current[1] value = int(current[2]) quantity = int(current[3]) p = product.Product(name, description, value, quantity) inventory.append(p) return inventory
def get_stock(self): """ Returns simple list of product references """ db = database.connect() cursor = database.get_cursor(db) stock = [] cursor.execute("select product_id \ from warehouses join warehouse_to_product \ on warehouses.id = warehouse_to_product.warehouse_id \ where warehouses.id = :warehouse_id", warehouse_id=self.get_id()) product_list = cursor.fetchall() if product_list: for product_id in product_list: stock.append(product.Product(int(product_id[0]))) database.disconnect(db) return stock
def parse_products(product_document): sizeco_soup = bs4.BeautifulSoup(product_document, "html.parser") products_soup = sizeco_soup.find_all("li", {"class": "productListItem"}) product_list = [] for product_soup in products_soup: url_data = product_soup.find("a", {"data-e2e": "product-listing-name"}) image = ((product_soup.find("img", {"class": ""})).attrs["src"]) url = "https://www.size.co.uk" + url_data.attrs["href"] title = url_data.get_text() price = (product_soup.find("span", {"data-e2e": "product-listing-price" })).get_text().replace("Â", "") pid = re.match(r".*?/([0-9]+)/.*?", url).group(1) product_list.append( prd.Product(title, url, pid, price, image, "size.co.uk")) product_list = product_list[:config.ppr] return product_list[::-1]
def get_products(self): db = database.connect() cursor = database.get_cursor(db) product_list = [] cursor.execute("select product_id from order_to_product \ where order_id = :input_id" , \ input_id = self.get_id()) returned_products = cursor.fetchall() if returned_products: for product_id_tuple in returned_products: product_list.append(product.Product(product_id_tuple[0])) database.disconnect(db) return product_list
def get_better_nutriscore_products(self, prod): ''' Return a list of all products in MySQL database with a better nutriscore than prod, from same category. ''' self.cursor = self.mydb.cursor(dictionary=True) substitutes_list = [] query = (f"SELECT product.*, category.name AS category FROM product " f"INNER JOIN category " f"ON product.cat_id = category.id " f"WHERE nutriscore < '{prod.nutriscore}'" f" AND category.name = '{prod.category}'") self.cursor.execute(query) for row in self.cursor: substitute = product.Product(row) substitutes_list.append(substitute) return substitutes_list
def get_products_and_quantities(self): db = database.connect() cursor = database.get_cursor(db) product_dict = {} cursor.execute("select product_id, quantity from order_to_product \ where order_id = :input_id" , \ input_id = self.get_id()) returned_products = cursor.fetchall() if returned_products: for product_id_tuple in returned_products: product_dict[product.Product( product_id_tuple[0])] = product_id_tuple[1] database.disconnect(db) return product_dict
async def __zadowolenie(product, content): soup = BeautifulSoup(content, "lxml") error_message = None price = None try: if soup.find("div", class_="b-offer_unavailable") is not None: error_message = "product unavailable" price = None else: price = soup.find("div", class_="m-priceBox_price m-priceBox_promo") price = float( price.text.replace(',', ".").strip(' \t\n\r').split()[0]) except Exception as e: price = None error_message = e finally: return p.Product(product.get_name(), price, product.get_url(), product.get_price_alert(), product.get_currency(), error_message)
async def __homedepot(product, content): soup = BeautifulSoup(content, "lxml") error_message = None price = None try: x = soup.find( "div", class_="price-format__large price-format__main-price") if x is None: error_message = "cant' get price" price = None else: s = x.find_all("span") price = float(f"{s[1].text}.{s[2].text}") except Exception as e: price = None error_message = e finally: return p.Product(product.get_name(), price, product.get_url(), product.get_price_alert(), product.get_currency(), error_message)
async def __etsy(product, content): soup = BeautifulSoup(content, "lxml") error_message = None price = None try: x = soup.find("p", class_="wt-text-title-03 wt-mr-xs-2") if x is None: error_message = "cant' get price" price = None else: price = float( re.search("[0-9]+\.[0-9]+", x.text.replace(",", ".")).group(0)) except Exception as e: price = None error_message = e finally: return p.Product(product.get_name(), price, product.get_url(), product.get_price_alert(), product.get_currency(), error_message)
async def __komputronik(product, content): soup = BeautifulSoup(content, "lxml") error_message = None price = None try: x = soup.find("div", class_="delivery grey disabled") if x is not None: price = None error_message = "product unavailable" else: price = soup.find("span", class_="proper") price = float( price.text.split('z')[0].replace(u'\xa0', "").replace(",", ".")) except Exception as e: price = None error_message = e finally: return p.Product(product.get_name(), price, product.get_url(), product.get_price_alert(), product.get_currency(), error_message)
def parse_products(product_document): products_list = [] footpatrol_soup = bs4.BeautifulSoup(product_document, "lxml") products_soup = footpatrol_soup.find_all("li", {"class": "fp-column-quarter"}) for product_soup in products_soup: url = (product_soup.find("a").attrs["href"]) image = (product_soup.find("img").attrs["src"]) price = (product_soup.find("h4", { "class": "fp-product-thumb-price" }).get_text().replace(" ", "").replace("\n", "")) title = re.sub(r"\s{3,25}", "", (product_soup.find("h4", { "class": "fp-product-thumb-title" }).get_text().replace("\n", ""))) pid = re.search("/([0-9]+)", url).groups()[0] url = "https://www.footpatrol.com" + url products_list.append( prd.Product(title, url, pid, price, image, "footpatrol.com")) products_list = products_list[:config.ppr] return products_list[::-1]
async def __alsen(product, content): soup = BeautifulSoup(content, "lxml") error_message = None price = 0 try: full = soup.find("div", class_="m-priceBox_new is-medium") if full is None: price = None error_message = "product unavailable" else: price = full.find("span", class_="m-priceBox_price") rest = full.find("span", class_="m-priceBox_rest") price = float(price.text) rest = float(rest.text) price += rest except Exception as e: price = None error_message = e finally: return p.Product(product.get_name(), price, product.get_url(), product.get_price_alert(), product.get_currency(), error_message)
def get_products_db(): products_data_base = [] try: conn = mysql.connector.connect(user='******', host='localhost', database='mysql') if conn.is_connected(): cursor = conn.cursor() cursor.execute("SELECT * FROM ASK_market_products") row = cursor.fetchone() while row is not None: products_data_base.append(product.Product(row[0], row[1], row[2], row[3], row[4], row[5])) row = cursor.fetchone() conn.commit() except Error as error: print(error) finally: conn.close() cursor.close() return products_data_base
async def __morele(product, content): soup = BeautifulSoup(content, "lxml") error_message = None price = None try: if soup.find( "button", class_= "add-to-cart__disabled btn btn-grey btn-block btn-sidebar btn-disabled" ) is not None: error_message = "product unavailable" else: price = soup.find("div", class_="product-price", id="product_price_brutto") price = float(price["content"]) except Exception as e: price = None error_message = e finally: return p.Product(product.get_name(), price, product.get_url(), product.get_price_alert(), product.get_currency(), error_message)