2015-06-21 46 views
2

我想從url保存圖像到特殊文件夾,例如'my_images',但不是默認的(我的* .py文件所在的位置)。有可能嗎? 因爲我的代碼使用* .py文件將所有圖像保存到文件夾。 這裏是我的代碼:將url從網址保存到特殊文件夾

import urllib.request 
from bs4 import BeautifulSoup 
import re 
import os 

BASE_URL = 'https://fachowiec.com/sklep/pl/products/index?Products_page=1&pageSize=15' 
def get_domain(url): 
    domain = re.findall(r'https:\W\W\w+\.\w+', url) 
    return domain[0] 


def get_html(url): 
    request = urllib.request.urlopen(url) 
    return request.read() 

def get_img(html): 
    soup = BeautifulSoup(html) 
    img_box = [] 
    imgs = soup.find_all('div', class_= 'pthumb') 

    for img in imgs: 
     img_box.append(get_domain(BASE_URL) + img.img['src']) 

    for img in img_box: 
     urllib.request.urlretrieve(img, os.path.basename(img)) 


def main(): 
    get_img(get_html('https://fachowiec.com/sklep/pl/products/index?Products_page=1&pageSize=15')) 

if __name__ == '__main__': 
    main() 

回答

2
def get_img(html): 
    soup = BeautifulSoup(html) 
    img_box = [] 
    imgs = soup.find_all('div', class_= 'pthumb') 

    for img in imgs: 
     img_box.append(get_domain(BASE_URL) + img.img['src']) 

    my_path = '/home/<username>/Desktop' # use whatever path you like 
    for img in img_box: 
     urllib.request.urlretrieve(img, os.path.join(my_path, os.path.basename(img))) 
0

你應該urllib.request.urlretrieve的第二個參數添加路徑名。類似下面:

urllib.request.urlretrieve(img, "PATH"+os.path.basename(img)) 

第二個參數,如果存在的話,則指定文件位置複製到(如果不存在,則位置爲與所生成的名稱的臨時文件)。