包含错误URL的URL请求Python

2024-10-03 15:24:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始为我正在做的一个项目编写Python。我编写了一个脚本,它获取图像的url列表(比如在txt文件中)并将它们全部下载。但是,列表中的一些url是旧的,不能再工作了。这会导致错误。另外,如果一个链接需要很长时间才能加载,它也会导致错误。在

代码: 进口urllib.请求在

import random


def downloadImageFromURL(url):

    name = random.randrange(1, 10000)

    full_name = str(name) + ".jpg"

    urllib.request.urlretrieve(url, full_name)


f = open('url.txt','r')

for row in range(0, 10):

   line = f.readline()

    try:

        downloadImageFromURL(line)

    except ConnectionError:

        print("Failed to open url.")

    print(line)

f.close()

新代码:

^{pr2}$

谢谢你!在


Tags: 项目代码nametxt脚本url列表错误
1条回答
网友
1楼 · 发布于 2024-10-03 15:24:07
import os
import requests
import shutil

outputDirectory = r"C:\Users\Joshua\Documents\Downloaded Media"

def sendRequest(url):
    try:
        page = requests.get(url, stream = True, timeout = 5)

    except Exception:
        pass

    else:
        if (page.status_code == 200):
            return page

    return False

def downloadImage(imageUrl: str, filePath: str):
    img = sendRequest(imageUrl)

    if (img == False):
        return False

    with open(filePath, "wb") as f:
        img.raw.decode_content = True

        try:
            shutil.copyfileobj(img.raw, f)
        except Exception:
            return False

    return True


URL = "https://upload.wikimedia.org/wikipedia/commons/b/b6/Image_created_with_a_mobile_phone.png"

imageName = URL.split("/")[-1] # Image_created_with_a_mobile_phone.png

# C:\Users\Joshua\Documents\Downloaded Media\Image_created_with_a_mobile_phone.png
imagePath = os.path.join(outputDirectory, imageName)

downloadImage(URL, imagePath)

相关问题 更多 >