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

文章目录

一、书籍推荐

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

三、运行结果

如下所示:

相关推荐
亿牛云爬虫专家1 天前
优化分布式采集的数据同步:一致性、去重与冲突解决的那些坑与招
分布式·爬虫·数据采集·爬虫代理·代理ip·数据同步·房地产
深蓝电商API2 天前
静态网页 vs 动态网页:爬虫该如何选择抓取策略?
爬虫
B站_计算机毕业设计之家2 天前
数据分析:Python懂车帝汽车数据分析可视化系统 爬虫(Django+Vue+销量分析 源码+文档)✅
大数据·爬虫·python·数据分析·汽车·可视化·懂车帝
孤狼warrior2 天前
爬虫+卷积神经网络项目实战解析——对图像狗的识别分类
人工智能·爬虫·神经网络·cnn·卷积神经网络
嫂子的姐夫3 天前
11-py调用js
javascript·爬虫·python·网络爬虫·爬山算法
kunge1v53 天前
学习爬虫第五天:自动化爬虫
爬虫·python·自动化
楼田莉子3 天前
python学习:爬虫+项目测试
后端·爬虫·python·学习
kunge1v53 天前
学习爬虫第三天:数据提取
前端·爬虫·python·学习
kunge1v54 天前
学习爬虫第四天:多任务爬虫
爬虫·python·学习·beautifulsoup
你也渴望鸡哥的力量么4 天前
爬虫学习笔记
笔记·爬虫·学习