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

文章目录

一、书籍推荐

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

三、运行结果

如下所示:

相关推荐
dme.1 小时前
Javascript之DOM操作
开发语言·javascript·爬虫·python·ecmascript
K哥爬虫3 小时前
【APP逆向百例】某品会 app 逆向分析
爬虫
巴里巴气6 小时前
selenium基础知识 和 模拟登录selenium版本
爬虫·python·selenium·爬虫模拟登录
凛铄linshuo1 天前
爬虫简单实操2——以贴吧为例爬取“某吧”前10页的网页代码
爬虫·python·学习
weixin_416639971 天前
爬虫工程师Chrome开发者工具简单介绍
前端·chrome·爬虫
科技苑2 天前
简单 Python 爬虫程序设计
爬虫
q567315232 天前
R语言初学者爬虫简单模板
开发语言·爬虫·r语言·iphone
泡泡以安3 天前
安卓高版本HTTPS抓包:终极解决方案
爬虫·https·安卓逆向·安卓抓包
q567315233 天前
Java Selenium反爬虫技术方案
java·爬虫·selenium
巴里巴气3 天前
Python爬虫用Clash软件设置代理IP
爬虫·python·tcp/ip