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

文章目录

一、书籍推荐

推荐本人书籍《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!!")

三、运行结果

如下所示:

相关推荐
IT毕设实战小研3 小时前
基于大数据的WTA职业网球赛事演变与竞技格局数据可视化分析
大数据·后端·爬虫·python·信息可视化·课程设计
2601_962382433 小时前
用“爬虫”抓取小红书内容侵权吗 福建法院判明边界
爬虫·数字经济·知识产权·不正当竞争·福建法院
Mycdn_WD4 小时前
从 AI 爬虫变多了到 AI 抓取开始分流,CDN 行业进入下一阶段
人工智能·爬虫·cdn·pcdn·城域网·pcdn资源招募
该逃避避15 小时前
爬虫代理配置指南:从0搭建Crawl4AI网页爬虫教程
爬虫
TechWayfarer16 小时前
Cloudflare 9·15新政倒计时:用IP风险画像识别AI爬虫,防止误伤Googlebot
网络·人工智能·爬虫·python·tcp/ip·网络安全
susplus1 天前
【HTTP协议】HTTP介绍及基础【C语言爬虫实现】
c语言·爬虫·http·万维网
绘梨衣5472 天前
AI技术栈全景指南_Prompt_RAG_爬虫_MCP
人工智能·爬虫·prompt
stolentime2 天前
OpenClaw 2.0 新手快速上手与实战指南
爬虫·python·ai·网络爬虫
玫瑰互动GEO2 天前
工程视角看GEO优化与SEO优化:爬虫排序 vs 大模型引用
人工智能·爬虫·搜索引擎
for_ever_love__2 天前
python爬虫: 数据解析
开发语言·爬虫·python·xpath