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

文章目录

一、书籍推荐

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

三、运行结果

如下所示:

相关推荐
MadPrinter2 小时前
FindQC 实战 (二):挑战 Google Lens —— 基于 Playwright 的隐匿模式与反爬虫机制构建
爬虫
Aerelin2 小时前
豆瓣数据采集案例
前端·爬虫·python·js·playwright
APIshop3 小时前
Java爬虫第三方平台获取1688关键词搜索接口实战教程
java·开发语言·爬虫
m***66734 小时前
网页数据抓取:融合BeautifulSoup和Scrapy的高级爬虫技术
爬虫·scrapy·beautifulsoup
星川皆无恙4 小时前
大数据爬虫可视化分析:基于Python的豆瓣书籍可视化分析系统的设计与实现
大数据·爬虫·python·架构·pycharm·django
嫂子的姐夫4 小时前
01-协程
爬虫·python·协程·多任务爬虫
h***04776 小时前
爬虫学习案例3
爬虫·python·学习
不叫猫先生6 小时前
基于AI代理浏览器的自动化数据爬取实践
人工智能·爬虫·自动化
艾莉丝努力练剑7 小时前
【Python基础:语法第二课】Python 流程控制详解:条件语句 + 循环语句 + 人生重开模拟器实战
人工智能·爬虫·python·pycharm
q***54757 小时前
初级爬虫实战——伯克利新闻
爬虫