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

文章目录

一、书籍推荐

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

三、运行结果

如下所示:

相关推荐
深蓝电商API2 小时前
反爬升级:WAF、行为检测、指纹追踪,我们该如何应对?
爬虫·waf·反爬
疏狂难除6 小时前
spiderdemo第四题
爬虫·okhttp·webassembly
好好好起个名真难21 小时前
爬虫 beautifulSoup 方法
爬虫·beautifulsoup
B站_计算机毕业设计之家1 天前
python舆情分析可视化系统 情感分析 微博 爬虫 scrapy爬虫技术 朴素贝叶斯分类算法大数据 计算机✅
大数据·爬虫·python·scrapy·数据分析·1024程序员节·舆情分析
B站_计算机毕业设计之家1 天前
Spark微博舆情分析系统 情感分析 爬虫 Hadoop和Hive 贴吧数据 双平台 讲解视频 大数据 Hadoop ✅
大数据·hadoop·爬虫·python·数据分析·1024程序员节·舆情分析
猫头虎1 天前
大模型训练中的关键技术与挑战:数据采集、微调与资源优化
人工智能·爬虫·数据挖掘·数据分析·网络爬虫·aigc·1024程序员节
失败又激情的man1 天前
爬虫逆向之X音a_bogus参数分析
爬虫·1024程序员节
爬虫程序猿2 天前
用 Python 给京东商品详情做“全身 CT”——可量产、可扩展的爬虫实战
开发语言·爬虫·python
盼哥PyAI实验室2 天前
《Python爬虫 + 飞书自动化上传》全流程详细讲解
爬虫·python·飞书
小白学大数据2 天前
Java爬虫性能优化:以喜马拉雅音频元数据抓取为例
java·爬虫·性能优化