I'm having a problem with this line of code I'm writing. Basically it takes the url of the picture or video from several Instagram posts and it downloads them one by one with the name 'name0.png','name1.png','name2.png' etc and then it shows all the names.
My only issue is it only downloads them to the folder where my code is located at, but i want to send them to a specific path.
The code is as follows:
def save_images(name,posts):
print("Downloading Images....")
pngnames = []
i = 1
#Load each post
for post in posts:
pngname = str(name) str(i) '.png'
driver.get(post)
wait = WebDriverWait(driver,6).until(EC.presence_of_element_located((By.CSS_SELECTOR,'#react-root > section > main > div > div.ltEKP > article > div > div.qF0y9.Igw0E.IwRSH.eGOV_._4EzTm > div > div > section.ltpMr.Slqrh > span._15y0l > button > div.QBdPU.B58H7 > svg > path')))
image = '#react-root > section > main > div > div > article > div > div._97aPb.wKWK0 > div > div > div.KL4Bh > img'
images = '#react-root > section > main > div > div.ltEKP > article > div > div._97aPb.wKWK0 > div > div.pR7Pc > div.qF0y9.Igw0E.IwRSH.eGOV_._4EzTm.O1flK.D8xaz.fm1AK.TxciK.yiMZG > div > div > div > ul > li:nth-child(2) > div > div > div > div.KL4Bh > img'
video = '#react-root > section > main > div > div.ltEKP > article > div > div._97aPb.wKWK0 > div > div > div > div > div > video'
#Get source URL of post
if driver.find_elements(By.CSS_SELECTOR,image):
downloadUrl = driver.find_element(By.CSS_SELECTOR,image)
elif driver.find_elements(By.CSS_SELECTOR,video):
downloadUrl = driver.find_element(By.CSS_SELECTOR, video)
elif driver.find_elements(By.CSS_SELECTOR,images):
downloadUrl = driver.find_element(By.CSS_SELECTOR,images)
else:
print("Couldnt get post url.")
continue
with open(pngname, 'wb') as file:
file.write(downloadUrl.screenshot_as_png)
i=i 1
pngnames.append(pngname)
return pngnames
What should I add for it to send these downloaded files to a specific folder?
'
CodePudding user response:
You can define pngname
however you want, including a path to any folder. os.path
is your friend when generating and manipulating path names. Note that the directory needs to exist, otherwise an error will be raised.
import os
path = "C:/Users/myself/Documents"
pngname = "myfile"
with open(os.path.join(path, pngname), 'wb') as f:
...