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

文章目录

一、书籍推荐

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

三、运行结果

如下所示:

相关推荐
李昊哲小课7 分钟前
Selenium 自动化测试教程
爬虫·selenium·测试工具
深蓝电商API1 小时前
Scrapy爬取Ajax动态加载页面三种实用方法
爬虫·python·scrapy·ajax
cnxy18814 小时前
Python爬虫进阶:反爬虫策略与Selenium自动化完整指南
爬虫·python·selenium
深蓝电商API15 小时前
Scrapy管道Pipeline深度解析:多方式数据持久化
爬虫·python·scrapy
噎住佩奇15 小时前
(Win11系统)搭建Python爬虫环境
爬虫·python
qq_3363139316 小时前
java基础-IO流(网络爬虫/工具包生成假数据)
java·爬虫·php
技术净胜18 小时前
Python 操作 Cookie 完全指南,爬虫与 Web 开发实战
前端·爬虫·python
癫狂的兔子21 小时前
【Python】【爬虫】复刻爬取豆瓣电影数据功能
爬虫
s_daqing1 天前
一、爬虫-控制台介绍
爬虫
袁袁袁袁满1 天前
Python爬虫下载PDF文件
爬虫·python·pdf·python爬虫下载pdf文件