Home > Back-end >  How can I save the images in sequence?
How can I save the images in sequence?

Time:12-18

How can I save the images in sequence, example:

image01 image02 image03

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager 

elements: driver.find_element(By. XPATH, "//img[@src]")

for element in elements:
     atributoSrc = imagem.get_attribute("src")
     #print(atributoSrc)
     urllib.request.urlretrieve(atributoSrc,r"C:\image\nome.jpg")

CodePudding user response:

In case images you want to save here are atributoSrc this can be done as following:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager 

images = []

elements: driver.find_element(By. XPATH, "//img[@src]")

for element in elements:
     atributoSrc = imagem.get_attribute("src")
     images.append(atributoSrc)
     urllib.request.urlretrieve(atributoSrc,r"C:\image\nome.jpg")

CodePudding user response:

You may need to declare one counter variable and dynamically name the image file by using f-Strings.

counter = 1
for element in elements:
     atributoSrc = element.get_attribute("src")
     file_name = f"image{counter:02d}.jpg"  # 00, 01, 02, ...
     urllib.request.urlretrieve(atributoSrc, f"C:\\image\\{file_name}")
     counter  = 1
  • Related