0

I need to see if a div with a particular class name has an image inside it. I am using.

picUrl=[]
        eachDiv =self.find_elements(By.XPATH,"//div[@class='NiLAwe y6IFtc R7GTQ keNKEd j7vNaf nID9nc']")
        for index, individualDiv in enumerate(eachDiv):
           
            if(individualDiv.find_element(By.XPATH,"//img[@class='tvs3Id QwxBBf']").get_attribute('src')):
                picUrl.append(individualDiv.find_element(By.XPATH,"//img[@class='tvs3Id QwxBBf']").get_attribute('src'))
                print('present')
            else:
                picUrl.append(" no pic ")
                print('not')
        return picUrl

but the condition never reaches inside the else condition even if the div doesn't have a tag with that class name.

Aavash Kc
  • 1
  • 1

1 Answers1

0

it'll depend on what the result of that expression inside your if-statement is:

if(individualDiv.find_element(By.XPATH,"//img[@class='tvs3IdQwxBBf']").get_attribute('src')):

in python for example if([]) is False but if([[]]) is True... I guess you need to make that expression a little more explicit. You could try something like

if len(individualDiv.find_elements(By.XPATH,"//img[@class='tvs3IdQwxBBf']")) > 0:

Or you could use find_by_xpath with a try except block as statet in this SO post, which is quite elegant.

Florian H
  • 3,052
  • 2
  • 14
  • 25