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

文章目录

一、书籍推荐

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

三、运行结果

如下所示:

相关推荐
qq_312920111 小时前
Nginx限流与防爬虫与安全配置方案
运维·爬虫·nginx·安全
华科云商xiao徐2 小时前
Java并发编程常见“坑”与填坑指南
javascript·数据库·爬虫
夜无霄3 小时前
安卓逆向(一)Ubuntu环境配置
linux·运维·爬虫·ubuntu
zhousenshan14 小时前
Python爬虫常用框架
开发语言·爬虫·python
deepwater_zone16 小时前
网络爬虫(web crawler)
爬虫
华科云商xiao徐1 天前
告别IP被封!分布式爬虫的“隐身”与“分身”术
爬虫·数据挖掘·数据分析
q567315231 天前
告别低效:构建健壮R爬虫的工程思维
开发语言·爬虫·r语言
一个天蝎座 白勺 程序猿2 天前
Python爬虫(47)Python异步爬虫与K8S弹性伸缩:构建百万级并发数据采集引擎
爬虫·python·kubernetes
华科云商xiao徐2 天前
告别低效:构建健壮R爬虫的工程思维
爬虫
熊猫钓鱼>_>3 天前
2025反爬虫之战札记:从robots.txt到多层防御的攻防进化史
开发语言·c++·爬虫