python 爬取指定图片并将图片下载到指定文件夹

"""
Version 1.1.0
Author lkk
Email lkk199404@163.com
date 2018-10-19 11:34
DESC 下载指定网页的图片到指定文件夹
"""
import requests
import os
from urllib import request
import re
res = request.urlopen("http://www.27270.com/beautiful/")
html = res.read()
with open("picture.html", 'wb') as f:
    f.write(html)
with open("picture.html", "rb") as f:
    msg = r'alt="(.*?)".*?src="(.*?)"'
    result = re.findall(msg, f.read().decode('gbk'))
    for i in result:
        url = ""
        root = "E:\my_test\day10_18\image/"
        path = root + i[0]+'.jpg'
        try:
            if not os.path.exists(root):
                os.mkdir(root)
                if os.path.exists(path):
                    r = requests.get(i[1])
                    # 如果发送了一个错误请求(一个 4XX 客户端错误,或者
                    # 5XX 服务器错误响应),我们可以通过Response.raise_for_status() 来抛出异常:
                    r.raise_for_status()
                    # 使用with语句可以不用自己手动关闭已经打开的文件流
                    with open(path, "wb") as e:  # 开始写文件,wb代表写二进制文件
                        e.write(r.content)
                    print("爬取完成")
            else:
                os.path.exists(path)
                r = requests.get(i[1])
                r.raise_for_status()
                # 使用with语句可以不用自己手动关闭已经打开的文件流
                with open(path, "wb") as e:  # 开始写文件,wb代表写二进制文件
                    e.write(r.content)
                print("爬取完成")
        except Exception as e:
            print("爬取失败:"+str(e))

 

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Python 中的 requests 和 BeautifulSoup 库来实现网页图片并放到指定文件夹的操作。具体步骤如下: 1. 使用 requests 库获需要的网页内容,并将其转换为 BeautifulSoup 对象。 2. 使用 BeautifulSoup 库解析 HTML 文档,找到所有需要图片链接。 3. 遍历所有图片链接,使用 requests 库下载图片,并保存到指定文件夹中。 下面是一个简单的示例代码,仅供参考: ```python import os import requests from bs4 import BeautifulSoup # 定义需要的网页 URL 和保存图片文件夹路径 url = "https://www.example.com" save_dir = "/path/to/save/folder" # 使用 requests 库获网页内容,并将其转换为 BeautifulSoup 对象 response = requests.get(url) soup = BeautifulSoup(response.content, "html.parser") # 使用 BeautifulSoup 库解析 HTML 文档,找到所有需要图片链接 img_tags = soup.find_all("img") img_urls = [img["src"] for img in img_tags] # 遍历所有图片链接,使用 requests 库下载图片,并保存到指定文件夹中 for img_url in img_urls: img_name = img_url.split("/")[-1] img_path = os.path.join(save_dir, img_name) img_response = requests.get(img_url) with open(img_path, "wb") as f: f.write(img_response.content) print(f"Saved image {img_path}") ``` 在上面的代码中,我们使用了 os 模块来拼接图片保存的路径,使用 requests 库来下载图片,并使用 with 语句来保证文件操作的安全性。需要注意的是,如果网页中包含了相对路径的图片链接,需要根据需要手动拼接完整的 URL。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值