skip to Main Content

I am using list for store all image urls from each product but my list adding previous image url in every new product. I want to clear list after write my csv and complete each loop. here is my code:

image_list = []

for page_num in range(1,6):
    ....my others code

   

            try:
                
                images = driver.find_elements_by_xpath("//img[@class='Image--fadeIn lazyautosizes Image--lazyLoaded']")
                for i in images:
                    image = i.get_attribute('data-original-src')
                    image_list.append("https:"+image)
                    print('######image: ',image)
            except:
                images = driver.find_element_by_css_selector("#shopify-section-product-template .Image--lazyLoaded")
                image = i.get_attribute('data-original-src')
                image_list.append("https:"+image)
                print(image)

            with open("product.csv", "a",encoding="utf-8") as f:
                            writeFile = csv.writer(f)
                            writeFile.writerow([image_list])

2

Answers


  1. You can clear the image_list list with

    image_list = []
    

    or

    image_list = list()
    

    After writing the list content into the CSV file.
    So your entire code can be as following:

    image_list = []
    
    for page_num in range(1,6):
        ....my others code
    
       
    
                try:
                    
                    images = driver.find_elements_by_xpath("//img[@class='Image--fadeIn lazyautosizes Image--lazyLoaded']")
                    for i in images:
                        image = i.get_attribute('data-original-src')
                        image_list.append("https:"+image)
                        print('######image: ',image)
                except:
                    images = driver.find_element_by_css_selector("#shopify-section-product-template .Image--lazyLoaded")
                    image = i.get_attribute('data-original-src')
                    image_list.append("https:"+image)
                    print(image)
    
                with open("product.csv", "a",encoding="utf-8") as f:
                                writeFile = csv.writer(f)
                                writeFile.writerow([image_list])
                image_list = []
    
    Login or Signup to reply.
  2. assign it to empty list

    image_list = []
    

    or use google for 5 seconds

    image_list.clear()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search