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

文章目录

一、书籍推荐

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

三、运行结果

如下所示:

相关推荐
专注API从业者5 小时前
《Go 语言高并发爬虫开发:淘宝商品 API 实时采集与 ETL 数据处理管道》
开发语言·后端·爬虫·golang
一个天蝎座 白勺 程序猿15 小时前
Python爬虫(3)HTML核心技巧:从零掌握class与id选择器,精准定位网页元素
前端·爬虫·html
jiaoxingk15 小时前
有关爬虫中数据库的封装——单线程爬虫
数据库·爬虫·python·mysql
知识中的海王1 天前
猿人学web端爬虫攻防大赛赛题第15题——备周则意怠-常见则不疑
爬虫·python
小白学大数据1 天前
如何避免爬虫因Cookie过期导致登录失效
开发语言·爬虫·python·scrapy
奋斗者1号1 天前
《Crawl4AI 爬虫工具部署配置全攻略》
网络·爬虫
Python×CATIA工业智造1 天前
爬虫技术入门:基本原理、数据抓取与动态页面处理
爬虫·python·pycharm
K哥爬虫2 天前
【验证码逆向专栏】某采购网,360 磐云盾、文字点选验证码逆向分析
爬虫
一个天蝎座 白勺 程序猿2 天前
Python爬虫(8)Python数据存储实战:JSON文件读写与复杂结构化数据处理指南
爬虫·python·json
Star abuse2 天前
Python爬虫课程实验指导书
开发语言·爬虫·python