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

文章目录

一、书籍推荐

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

三、运行结果

如下所示:

相关推荐
fly spider9 小时前
AI 到底是怎么访问网页的?从爬虫、Browser Agent 到 Computer Use
人工智能·爬虫
Keano Reurink15 小时前
SEO数据管道:用Airflow搭建自动化工作流
运维·人工智能·爬虫·搜索引擎·自动化·ai编程·seo
跨境数据猎手17 小时前
代购系统技术选型全复盘:Laravel / Go / 自研 / SaaS 怎么选
爬虫·php·laravel
深蓝电商API21 小时前
直播电商弹幕实时抓取:WebSocket协议分析与数据解析
爬虫
weixin199701080162 天前
[特殊字符] 人工抓取数据革命:从“人肉爬虫”到“智能数据工厂”全面转型指南
开发语言·爬虫·python
川冰ICE2 天前
Python爬虫实战㉘|综合实战3,新闻热点追踪与舆情分析系统
开发语言·爬虫·python
devnullcoffee2 天前
亚马逊Browse Node类目树数据采集实战:从PA-API到分布式爬虫
分布式·爬虫·亚马逊数据采集 api·亚马逊类目树数据·亚马逊 browse node·amazon 数据 api
aP8PfmxS23 天前
网络爬虫是自动从互联网上采集数据的程序
爬虫
Serendipity_Carl3 天前
爬虫实战进阶-穷游论坛网清洗与可视化分析
爬虫·python·数据可视化·数据清洗