简体   繁体   English

将图像从 url 保存到特殊文件夹

[英]Save image from url to special folder

I want to save images from url to special folder, for example 'my_images', but not to default(where my *.py file is).我想将图像从 url 保存到特殊文件夹,例如“my_images”,但不是默认(我的 *.py 文件所在的位置)。 Is it possible to make it?有可能做到吗? Because my code saves all images to folder with *.py file.因为我的代码将所有图像保存到带有 *.py 文件的文件夹中。 Here is my code:这是我的代码:

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()
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)))

You should add the pathname in second parameter of urllib.request.urlretrieve.您应该在 urllib.request.urlretrieve 的第二个参数中添加路径名。 Something like below:像下面这样:

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

The second argument, if present, specifies the file location to copy to (if absent, the location will be a tempfile with a generated name).第二个参数(如果存在)指定要复制到的文件位置(如果不存在,该位置将是具有生成名称的临时文件)。

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

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