我定义了以下功能以检查新书的数量。
def getNewSellerNumber(isbn):
res=requests.get('http://www.amazon.com/dp/'+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
它工作正常但我将来可能会添加另一个CSS选择器。这意味着我的If statemenst将会成长。为了存储CSS选择器,我创建了一个列表如下,但这次,它在每个条件中都返回None,因为其中一个选择器总是错误的。
def getSellers(isbn):
res = requests.get('http://www.amazon.com/dp/'+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)
如何组合或缩短这些if语句?
循环后移动返回无
for i in selectors:
elements = soup.select(i)
if elements:
return elements[0].text
return None