爬虫项目(四):抓取网页所有图片

文章目录

一、书籍推荐

推荐本人书籍《Python网络爬虫入门到实战》 ,详细介绍见👉: 《Python网络爬虫入门到实战》 书籍介绍

二、完整代码

原理:抓取该链接中所有的图片格式。基于selenium来获取,自动下载到output文件夹中。

csharp 复制代码
from selenium import webdriver
import requests as rq
import os
from bs4 import BeautifulSoup
import time

# Enter Path : chromedriver.exe
# Enter URL : http://www.netbian.com/meinv/index_2.htm

path = input("Enter Path : ")
url = input("Enter URL : ")
output = "output"


def get_url(path, url):
    driver = webdriver.Chrome(executable_path=r"{}".format(path))
    driver.get(url)
    print("loading.....")
    res = driver.execute_script("return document.documentElement.outerHTML")
    return res


def get_img_links(res):
    soup = BeautifulSoup(res, "lxml")
    imglinks = soup.find_all("img", src=True)
    return imglinks


def download_img(img_link, index):
    try:
        extensions = [".jpeg", ".jpg", ".png", ".gif"]
        extension = ".jpg"
        for exe in extensions:
            if img_link.find(exe) > 0:
                extension = exe
                break
        img_data = rq.get(img_link).content
        with open(output + "\\" + str(index + 1) + extension, "wb+") as f:
            f.write(img_data)
        f.close()
    except Exception:
        pass


result = get_url(path, url)
time.sleep(60)
img_links = get_img_links(result)
if not os.path.isdir(output):
    os.mkdir(output)
for index, img_link in enumerate(img_links):
    img_link = img_link["src"]
    print("Downloading...")
    if img_link:
        download_img(img_link, index)
print("Download Complete!!")

三、运行结果

如下所示:

相关推荐
susplus4 小时前
【HTTP协议】HTTP介绍及基础【C语言爬虫实现】
c语言·爬虫·http·万维网
绘梨衣54719 小时前
AI技术栈全景指南_Prompt_RAG_爬虫_MCP
人工智能·爬虫·prompt
stolentime1 天前
OpenClaw 2.0 新手快速上手与实战指南
爬虫·python·ai·网络爬虫
玫瑰互动GEO1 天前
工程视角看GEO优化与SEO优化:爬虫排序 vs 大模型引用
人工智能·爬虫·搜索引擎
for_ever_love__1 天前
python爬虫: 数据解析
开发语言·爬虫·python·xpath
傻啦嘿哟1 天前
某米应用商店爬虫:爬取APP榜单数据,分析应用市场格局
爬虫
德迅云安全-上官2 天前
业务接口对抗爬虫与批量薅羊毛实战手册:拨开接口层攻击迷雾,搭建业务接口全链路安全防护体系
爬虫·安全
心中有你02142 天前
Python爬虫实战:京东商品数据爬取+可视化分析
开发语言·爬虫·python
tang777892 天前
爬虫代理池搭建全流程:从IP筛选、去重到自动切换(附完整落地代码)
爬虫·网络协议·tcp/ip·代理ip池·爬虫代理池
进击的雷神3 天前
网站 SEO 功能怎么测:从手工检查到自动化脚本的实战思路
运维·爬虫·自动化·官网seo·收录