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

文章目录

一、书籍推荐

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

三、运行结果

如下所示:

相关推荐
B站计算机毕业设计超人8 小时前
计算机毕业设计Python+Flask微博情感分析 微博舆情预测 微博爬虫 微博大数据 舆情分析系统 大数据毕业设计 NLP文本分类 机器学习 深度学习 AI
爬虫·python·深度学习·算法·机器学习·自然语言处理·数据可视化
waterHBO11 小时前
python 爬虫 selenium 笔记
爬虫·python·selenium
bugtraq20211 天前
闲鱼网页版开放,爬虫的难度指数级降低。
爬虫
Bigcrab__1 天前
Python3网络爬虫开发实战(15)Scrapy 框架的使用(第一版)
爬虫·python·scrapy
九月镇灵将1 天前
爬虫逆向学习(六):补环境过某数四代
爬虫·补环境·瑞数
kngines1 天前
【PLW004】基于Python网络爬虫与推荐算法的新闻推荐平台v1.0(Python+Django+NLP+Vue+MySQL前后端分离)
爬虫·python·nlp·推荐算法
walk walk2 天前
免费爬虫软件“HyperlinkCollector超链采集器v0.1”
爬虫
亿牛云爬虫专家2 天前
如何通过subprocess在数据采集中执行外部命令 —以微博为例
爬虫·python·数据采集·多线程·代理ip·subprocess·微博