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

文章目录

一、书籍推荐

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

三、运行结果

如下所示:

相关推荐
Kratzdisteln6 小时前
【Web-Crawler-Steamdt】以项目文件steamdt_crawler.py学习python爬虫
爬虫·python·学习
嫂子的姐夫6 小时前
03-自动化小案例
爬虫·自动化·drissionpage
嫂子的姐夫6 小时前
02-DrissionPage
爬虫·drissionpage·自动化爬虫
Pyeako7 小时前
操作HTML网页(PyCharm版)
爬虫·python·html
傻啦嘿哟8 小时前
学术爬虫实战:构建知网论文关键词共现网络的技术指南
网络·爬虫
几分醉意.10 小时前
Bright Data AI Scraper Studio:用一句Prompt,自动生成企业级爬虫架构
人工智能·爬虫·prompt
sugar椰子皮1 天前
【爬虫框架-3】闭包的用法
爬虫
齐齐大魔王1 天前
python爬虫学习进程(四)
爬虫·python·学习
毕设源码-钟学长1 天前
【开题答辩全过程】以 基于Python爬虫的二手房信息爬取及分析为例,包含答辩的问题和答案
开发语言·爬虫·python
Glommer1 天前
Akamai 逆向思路
javascript·爬虫·逆向