jeudi 30 avril 2020

Can I write a loop such that it recognizes when a link exists or not?

I am writing a script that goes onto a website and goes through and checks if a specifi item name exists within the site's code.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
import time
import clipboard
import requests
import bs4 as bs
from bs4 import SoupStrainer
from splinter import Browser
import helpers
from selenium.common.exceptions import ElementNotInteractableException
from config import INFO
#This looks for the product based on what the category is 
#Uses the dictionary INFO, which has product information
    def findProduct(self):

        try:
            category =  str(INFO['category'])
            source = requests.get("http://www.supremenewyork.com/shop/all/"+category).text
            soup = bs.BeautifulSoup(source, 'lxml')
            temp_link = []
            temp_tuple = []
            for link in soup.find_all('a', href=True):
                temp_tuple.append((link['href'], link.text))
            for i in temp_tuple:
                if  INFO['product'] in i[1] or INFO['color'] in i[1]: 
                    temp_link.append(i[0])
                    #print(temp_link)

            #This creates end of the final link
            self.final_link = list(
                set([x for x in temp_link if temp_link.count(x) == 2]))[0]


            #Concatenates the previous link w/ the website
            link = 'http://www.supremenewyork.com'+str(self.final_link)
            print(link,end='\n')
            print("Link Copied to Clipboard")
        except IndexError:
            print('Hasn\'t dropped yet...') 


    BOT = Bot(**INFO) #INFO is just a dictionary which has product information
    found_product = False
    counter = 1
    max_iter = 15
    while not found_product and counter < max_iter:
        found_product = BOT.findProduct()
        print("We tried ",counter," times.")
        counter +=1
        print(type(BOT.findProduct()))
        print('Hi')
        if isinstance(BOT.findProduct(), type(None)) == True:
            print('found it')
            break
        else: print('Could not find it')
        continue

I understand that my code will always default to "found it" because the type of the function is the NoneType, but I would like the loop to check whether or not the link that gets copied to the clipboard exists. If it does I want the code to break off.

I have tried

if (print(BOT.findProduct()) == None):
            print('found it')
            break
        else: print('Could not find it')
        continue

And while I understand why it doesn't work, I hope that whoever is reading this can see what I'm going for.

If anyone could help I would greatly appreciate it.

Aucun commentaire:

Enregistrer un commentaire