urlib.request.retrieve以变量为参数向用户指定的文件发送。

问题描述 投票:0回答:1

作为我的任务的一部分,我应该创建这个自动的python下载器。它的工作原理是从一个名为 "urls.txt "的文本文件中检索链接。我的部分工作是让我们把这些链接下载到一个指定的目的地,并打印出链接被下载到用户指定的文件中。到目前为止,我已经尝试了用户指定位置的部分,但我的老师不能帮我太多,所以我在这里。脚本自带一个错误函数,如果 "try "异常没有被满足就会显示。总之这就是代码。

import os.path
import urllib.request


linksFile = input("Please specify the path to the text file:")
f = open(linksFile + '.txt', 'r')
links = f.readlines()
for link in links:


    # Get one line of text (e.g. http://server/files/grades.doc),
    # then get the filename from the end of the URL
    link = link.strip()
    print(link)
    filename = link.rsplit('/', 1)[-1]
    print(filename)

    # Does this file exist in this folder? If not, download it
    if not (os.path.isfile(filename)):
        print('Downloading: ' + filename)

        try:
            urllib.request.urlretrieve(filename, '/Users/mattt/Documents/python.script.downloads')
            print('Downloading: ' + filename)
            print("File size was", os.path.getsize(filename))
        except Exception as inst:
            print(inst)
            print('  Encountered unknown error. Continuing.')

    # File exists; don't download
    else:
        print("This file exists already.")

# End of program
print("Finished downloading.")

问题是,由于某些原因,它抛出了这个错误信息。

Please specify the path to the text file:C:/Users/mattt/documents/urls

http://www.brickshelf.com/gallery/g2/Mugs/20050213/mugs_050213_014.jpg
mugs_050213_014.jpg
Downloading: mugs_050213_014.jpg
unknown url type: 'mugs_050213_014.jpg'
Encountered unknown error. Continuing.

http://www.brickshelf.com/gallery/g2/Mugs/20050213/mugs_050213_008b.jpg
mugs_050213_008b.jpg
Downloading: mugs_050213_008b.jpg
unknown url type: 'mugs_050213_008b.jpg'
Encountered unknown error. Continuing.

http://www.brickshelf.com/gallery/g2/Mugs/20050213/mugs_050213_006.jpg
mugs_050213_006.jpg
Downloading: mugs_050213_006.jpg
unknown url type: 'mugs_050213_006.jpg'
Encountered unknown error. Continuing.

Finished downloading.

Process finished with exit code 0
python pycharm
1个回答
0
投票

你只传递了文件名,你想在下载时传递图片的完整URL。

urllib.request.urlretrieve(link, '/Users/mattt/Documents/python.script.downloads')
© www.soinside.com 2019 - 2024. All rights reserved.