Python爬虫实战:解决FileNotFoundError错误并批量下载图片

在使用Python爬虫下载图片时,经常会遇到FileNotFoundError错误,这是因为代码尝试保存图片到一个不存在的文件夹。本文将介绍如何解决这个问题,并提供一个完整的代码示例,演示如何使用requestsBeautifulSoupos模块批量下载图片。

问题分析

出现FileNotFoundError错误的原因是,代码中指定保存图片的路径不存在。例如,下面的代码尝试将图片保存到img/文件夹,但如果该文件夹不存在,就会抛出异常:pythonimport requestsfrom bs4 import BeautifulSoup

def download(url): res = requests.get(url) img = res.content filename = 'img/' + url.split('/')[-1] with open(filename , 'wb') as f: f.write(img)

... 其他代码 ...

解决方案

解决方法很简单,只需要在保存图片之前,先检查目标文件夹是否存在,如果不存在则创建它。可以使用os模块的os.path.exists()方法检查文件夹是否存在,使用os.makedirs()方法创建文件夹。

代码示例

以下代码演示了如何使用requestsBeautifulSoupos模块批量下载图片,并解决了FileNotFoundError错误:pythonimport requestsfrom bs4 import BeautifulSoupimport os

def download(url): res = requests.get(url) img = res.content filename = 'img/' + url.split('/')[-1] with open(filename , 'wb') as f: f.write(img)

def get_html(): url = 'http://www.netbian.com/index_519.htm' headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'} res = requests.get(url ,headers = headers) res.encoding = 'gbk' if res.status_code == 200: html = res.text soup = BeautifulSoup(html,'lxml') all_list = soup.find(class_ = 'list') all_img = all_list.find_all('img') # 检查文件夹是否存在,如果不存在则创建 if not os.path.exists('img'): os.makedirs('img') for img in all_img: src = img['src'] download(src)

if name == 'main': get_html()

代码解读:

  1. 导入模块: 导入requestsBeautifulSoupos模块。2. download(url)函数: - 接收图片链接作为参数。 - 使用requests.get()方法下载图片。 - 使用os.path.split()方法获取文件名。 - 使用with open(filename, 'wb') as f打开文件,并将图片内容写入文件。3. get_html()函数: - 定义目标网页的URL和请求头。 - 使用requests.get()方法发送请求,并指定编码为gbk。 - 使用BeautifulSoup解析网页内容。 - 使用find()find_all()方法定位图片元素。 - 关键: 使用os.path.exists('img')检查img文件夹是否存在,如果不存在则使用os.makedirs('img')创建。 - 遍历图片列表,调用download()函数下载每张图片。

总结

本文介绍了Python爬虫下载图片时遇到FileNotFoundError错误的原因和解决方法,并提供了一个完整的代码示例。通过使用os模块检查和创建文件夹,可以避免这个错误,确保图片能够成功下载。

Python爬虫实战:解决FileNotFoundError错误并批量下载图片

原文地址: https://www.cveoy.top/t/topic/fRmG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录