随笔 - 633,  文章 - 0,  评论 - 13,  阅读 - 48万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

代码

复制代码
import os
import requests
from bs4 import BeautifulSoup

# 指定要爬取的网址
url = 'https://www.baidu.com/'

# 请求网页内容
response = requests.get(url)
response.raise_for_status()  # 如果请求失败,将抛出异常

# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(response.text, 'html.parser')

# 创建存储图片的文件夹
folder_name = r'F:\jingguan\tu'
if not os.path.exists(folder_name):
    os.makedirs(folder_name)

# 找到网页中的所有<img>标签
img_tags = soup.find_all('img')

# 遍历所有的<img>标签,下载图片
for img in img_tags:
    src = img.get('src')  # 获取图片的src属性
    if src:
        # 完整的图片URL
        img_url = src if src.startswith(('http:', 'https:')) else url + src
        try:
            # 发送请求获取图片内容
            img_response = requests.get(img_url)
            img_response.raise_for_status()

            # 图片文件名
            img_name = os.path.join(folder_name, img_url.split('/')[-1])
            with open(img_name, 'wb') as f:
                f.write(img_response.content)
            print(f"图片已下载:{img_name}")
        except requests.exceptions.RequestException as e:
            print(f"下载图片时出错:{e}")

print("图片下载完成。")
复制代码

 

posted on   大话人生  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2022-04-28 人脸训练
2020-04-28 Vue -路由(Vue -Router)
2020-04-28 Vue常用的UI组件-Elment(PC端Vue组件库)(饿了么组件)(推荐)
2020-04-28 Vue常用的UI组件-ant-design-vue
2020-04-28 Vue常用的UI组件-Mint UI(移动端Vue组件库)(饿了么组件)
2020-04-28 Vue常用的UI组件-vant(轻量、可靠的移动端Vue组件库)(推荐)
点击右上角即可分享
微信分享提示