【python】运用Request库实现爬虫
    		       		warning:
    		            这篇文章距离上次修改已过445天,其中的内容可能已经有所变动。
    		        
        		                
                
import requests
 
def download_image(url, file_path):
    response = requests.get(url)
    if response.status_code == 200:
        with open(file_path, 'wb') as file:
            file.write(response.content)
        print(f"Image saved to: {file_path}")
    else:
        print(f"Failed to download image: {response.status_code}")
 
# 使用示例
image_url = "http://example.com/image.jpg"
save_path = "downloaded_image.jpg"
download_image(image_url, save_path)这段代码定义了一个download_image函数,它接受一个图片URL和要保存的文件路径作为参数。使用requests.get方法下载图片,并检查响应状态码。如果状态码为200,表示下载成功,然后将图片内容写入指定的文件中。最后提供了一个使用示例来展示如何使用这个函数。
评论已关闭