Search code examples
pythonpython-3.xtry-catch

How to I specify a repeat if Try and Except yield no results?


I have just completed coding my first real program in python! It's a bot that takes a string from a google spreadsheet, inputs it into the query box on a website, greps the link from the result, clicks on it, and then greps some information from the resulting page. I will be happy to share it soon, but the problem now is that every so often it searches for something that yields no results and throws an error for my Try and Except clauses. The resulting searched link comes in two different forms depending on how many search results there are, so my Try and Except clauses are:

    try:
        BCell = driver.find_element(By.XPATH, '//a[contains(@href, "/documents/business.html?fileNumber=")]')
    except:
        BCell = driver.find_element(By.XPATH, '//a[contains(@href, "/documents/trade.html?fileNumber=")]')

And if I could somehow use a "finally" term or something to simply search for the next business and get that link before continuing, the way it decides what to enter into the box is by using ABName defined as:

ABName = sheet.cell(X, 2).value

X being the current query input, 2 being the column of inputs - I basically only want to X+=1, and then run the script over again rather than pandas and/or selenium failing due to not finding the clickable link element.

The next code after finding the search query is:

link = BCell.get_attribute('href')

So the methods I've tried to make it simply continue yielded in a Get Atrribute - Not Found Error.


Solution

  • The best way to make the code continue without fail was to essentially put all the looped code in a try/except clause as:

        try:
            try:
                BCell = driver.find_element(By.XPATH, '//a[contains(@href, "/documents/business.html?fileNumber=")]')
            except:
                BCell = driver.find_element(By.XPATH, '//a[contains(@href, "/documents/trade.html?fileNumber=")]')
        except:
            print("Business '"+ABName+"' Not Found!" )
        #updates X so that it goes to the next business upon the next loop.
            X+=1
            continue
    
        try:
           all
           the
           rest
           of
           the
           code
           #
           #
           ...
        except:
           continue
    
        #long wait after all searches as to not load the site too many times
        time.sleep(10)
        
        driver.quit()
    

    Now all I have to do is figure out how to make the new chromedrivermanager run in headless mode so that it will stop opening chrome instances on my PC! lol