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

文章目录

一、书籍推荐

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

三、运行结果

如下所示:

相关推荐
0思必得04 小时前
[Web自动化] Selenium设置相关执行文件路径
前端·爬虫·python·selenium·自动化
深蓝电商API13 小时前
异步爬虫防封策略:随机User-Agent与延时
爬虫·python
深蓝电商API13 小时前
asyncio+playwright实现超高性能异步爬虫
爬虫·python
冰敷逆向13 小时前
京东h5st纯算分析
java·前端·javascript·爬虫·安全·web
小白学大数据14 小时前
Python爬虫实现无限滚动页面的自动点击与内容抓取
开发语言·爬虫·python·pandas
0思必得014 小时前
[Web自动化] Selenium处理Cookie
前端·爬虫·python·selenium·自动化
喵手14 小时前
Python爬虫实战:房价/租金指数时间序列爬虫实战 - 从多页采集到趋势分析的完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·房价/租金指数时间序列·多页采集到趋势分析·采集结果sqlite到处
B2_Proxy15 小时前
如何使用代理服务解决“您的 ASN 被阻止”错误:全面策略分析
网络·爬虫·网络协议·tcp/ip·安全·代理模式
EdgeOne边缘安全加速平台15 小时前
一键管控 AI 爬虫,腾讯 EdgeOne 基础 Bot 管理能力免费开放
人工智能·爬虫
喵手16 小时前
Python爬虫实战:房产数据采集实战 - 链家二手房&安居客租房多页爬虫完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·房产数据采集·链家二手房/安居客房源采集·采集结果sqlite导出