lundi 18 décembre 2017

Combining or shortening If statements in python

I defined the following function in order to check the number of new books.

def getNewSellerNumber(isbn):
    res=requests.get('http://ift.tt/Y44pQY'+isbn)
    soup = bs4.BeautifulSoup(res.text,'html.parser')
    elements=soup.select('#mediaOlp > div > div > div > div.a-fixed-right-grid-col.accordion-row-left-content.a-col-left > div:nth-of-type(2) > div > span:nth-of-type(1) > a')

    if elements == []:
        elements2=soup.select('#mediaOlp > div > div > div.a-fixed-right-grid-col.accordion-row-left-content.a-col-left > div:nth-of-type(2) > div > span:nth-of-type(1) > a')
        if elements2 == []:
            elements3=soup.select('span > span:nth-of-type(3) > span.olp-new.olp-link > a')
            if elements3 ==[]:
                return None
            else:
                return elements3[0].text
        else:
            return elements2[0].text
    else:
        return elements[0].text

It works fine but I may add another CSS selector in the future. That means my If statemenst are going to grow. I made a list as following in order to stores CSS selectors but this time, it returns None in every condition since one of the selectors are always wrong.

def getSellers(isbn):
    res = requests.get('http://ift.tt/Y44pQY'+isbn)
    soup = bs4.BeautifulSoup(res.text,'html.parser')
    selectors = ['#mediaOlp > div > div > div > div.a-fixed-right-grid-col.accordion-row-left-content.a-col-left > div:nth-of-type(2) > div > span:nth-of-type(1) > a','#mediaOlp > div > div > div.a-fixed-right-grid-col.accordion-row-left-content.a-col-left > div:nth-of-type(2) > div > span:nth-of-type(1) > a','span > span:nth-of-type(3) > span.olp-new.olp-link > a' ]
    for i in selectors:
        elements = soup.select(i)
        if elements ==[]:
            return None
        else:
            print(elements[0].text)

How can I combine or shorten these if statements?

Aucun commentaire:

Enregistrer un commentaire