简体   繁体   English

下载图片到特定文件夹 Selenium Python

[英]Download pictures to specific folder Selenium Python

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.基本上它从几个 Instagram 帖子中获取图片或视频的 url,然后用名称“name0.png”、“name1.png”、“name2.png”等一个一个地下载它们,然后显示所有名称。

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?我应该添加什么才能将这些下载的文件发送到特定文件夹?

' '

You can define pngname however you want, including a path to any folder.您可以根据需要定义pngname ,包括任何文件夹的路径。 os.path is your friend when generating and manipulating path names. os.path在生成和操作路径名时是你的朋友。 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:
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM