cmd中运行

>python untitled2.py    图片的网站

import requests
import threading
from bs4 import BeautifulSoup
import sys
import os

if len(sys.argv) != 2:
    print("Usage : " )
    print(" python main.py [URL]" )
    exit(1)
# config-start
url = sys.argv[1]
threadNumber = 20
# 设置线程数 # config-end
def getContent(url):
    try:
        response = requests.get(url)
        response.raise_for_status()
        response.encoding = response.apparent_encoding
        return response.text
    except Exception  as e:
        print(e)
        return str(e)
def getTitle(soup):
    try:
        return soup.title.string
    except:
        return "UnTitled"
def getImageLinks(soup):
    imgs = soup.findAll("img")
    result = []
    for img in imgs:
        try:
            src = img['src']
            if src.startswith("http"):
                result.append(img['src'])
            else:
                result.append(domain + img['src'])
        except:
            continue
    return result
def makeDirectory(dicName):
    if not os.path.exists(dicName):
        os.mkdir(dicName)
def downloadImage(imgUrl,savePath):
    local_filename = imgUrl.split('/')[-1]
    local_filename = formatFileName(local_filename)
    r = requests.get(imgUrl, stream=True)
    counter = 0
    if not savePath.endswith("/"):
        savePath += "/"
    f = open(savePath + local_filename, 'wb')
    for chunk in r.iter_content(chunk_size=1024):
        if chunk:
            f.write(chunk)
            f.flush()
            counter += 1
    f.close()
def formatFileName(fileName):
    fileName = fileName.replace("/","_")
    fileName = fileName.replace("\\","_")
    fileName = fileName.replace(":","_")
    fileName = fileName.replace("*","_")
    fileName = fileName.replace("?","_")
    fileName = fileName.replace("\"","_")
    fileName = fileName.replace(">","_")
    fileName = fileName.replace("<","_")
    fileName = fileName.replace("|","_")
    fileName = fileName.replace(" ","_")
    return fileName
def threadFunction(imgSrc,directoryName):
    downloadImage(imgSrc,directoryName)
    
class myThread (threading.Thread):
    def __init__(self, imgSrc, directoryName):
        threading.Thread.__init__(self)
        self.imgSrc = imgSrc
        self.directoryName = directoryName
    def run(self):
        threadFunction(self.imgSrc, self.directoryName)
def getPrefix(url):
    # http://doamin/xxx.jpg
    return ''.join(i+"/" for i in url.split("/")[0:4])
def getDomain(url):
    return ''.join(i+"/" for i in url.split("/")[0:3])
content = getContent(url)
prefix = getPrefix(url)
domain = getDomain(url)
soup = BeautifulSoup(content, "html.parser")
images = getImageLinks(soup)
title = getTitle(soup)
title = formatFileName(title)
print(u"页面标题 : " , title )
print(u"本页图片数量 :",len(images))
print(u"正在创建文件夹以用来保存所有图片")
makeDirectory(title)
threads = []
for image in images:
    print(u"图片地址 : " + image)
    threads.append(myThread(image, title))
for t in threads:
    t.start()
    while True:
        if(len(threading.enumerate()) < threadNumber):
            break
print(u"所有图片已加入下载队列 ! 正在下载...")

python多线程采集图片的更多相关文章

  1. Python多线程采集百度相关搜索关键词

    百度相关搜索关键词抓取,读取txt关键词,导出txt关键词 #百度相关搜索关键词抓取,读取txt关键词,导出txt关键词   # -*- coding=utf-8 -*- import request ...

  2. python多线程采集

    import requests import json import threading Default_Header = { #具体请求头自己去弄 } _session=requests.sessi ...

  3. python多线程批量下载远程图片

    python多线程使用场景:多线程采集, 以及性能测试等 . 数据库驱动类-简单封装下 mysqlDriver.py #!/usr/bin/python3 #-*- coding: utf-8 -*- ...

  4. Python查询MySQL进行远程采集图片实例

    这是四五年以前做小说站采集图片时写过唯一一次 Python 代码 #!/usr/bin/python #-*-coding:utf-8-*- import MySQLdb, os, socket, t ...

  5. python多线程爬虫+批量下载斗图啦图片项目(关注、持续更新)

    python多线程爬虫项目() 爬取目标:斗图啦(起始url:http://www.doutula.com/photo/list/?page=1) 爬取内容:斗图啦全网图片 使用工具:requests ...

  6. Python 多线程教程:并发与并行

    转载于: https://my.oschina.net/leejun2005/blog/398826 在批评Python的讨论中,常常说起Python多线程是多么的难用.还有人对 global int ...

  7. 使用file_get_content系列函数和使用curl系列函数采集图片的性能对比

    由于公司的一个汽车网站的后台的汽车内容都是主要是来自与汽车之家的,编辑的同事们必须天天手动去对着汽车之家来添加汽车,实在是太蛋疼了.于是乎,为了改变这种状况,作为一个开发码农,我的任务就来了...那就 ...

  8. Python多线程Selenium跨浏览器测试

    前言 在web测试中,不可避免的一个测试就是浏览器兼容性测试,在没有自动化测试前,我们总是苦逼的在一台或多台机器上安装N种浏览器,然后手工在不同的浏览器上验证主业务流程和关键功能模块功能,以检测不同浏 ...

  9. 13行代码实现:Python实时视频采集(附源码)

    一.前言 本文是<人脸识别完整项目实战>系列博文第3部分:程序设计篇(Python版),第1节<Python实时视频采集程序设计>,本章内容系统介绍:基于Python+open ...

随机推荐

  1. WLC license管理

    关于控制器的license,可以参考对应平台的Datasheet: Cisco 2504 WLC Cisco 3504 WLC Cisco 5508 WLC Cisco 5520 WLC Cisco ...

  2. 从0到1了解 CI/CD

    现代软件开发的需求加上部署到不同基础设施的复杂性使得创建应用程序成为一个繁琐的过程.当应用程序出现规模性增长,开发团队人员变得更分散时,快速且不断地生产和发布软件的流程将会变得更加困难.为了解决这些问 ...

  3. Spring 7种事务传播类型

    转载:https://www.cnblogs.com/originate918/p/6226342.html PROPAGATION_REQUIRED及其他6种事务传播行为种类. Spring在Tra ...

  4. layui-表格宽度自适应

    不设置表格宽度,表格默认全屏 可以通过以下方式设置表格宽度

  5. java 面试题 mybatis 篇

    1. 一级缓存和二级缓存? 一级缓存策略: 二级缓存策略: 2. 缓存回收策略 LRU –  最近最少使用的:移除最长时间不被使用的对象. FIFO –  先进先出:按对象进入缓存的顺序来移除它们. ...

  6. python csv 读写操作

    import csv def read_csvList(path="./datasets/test.csv")->list: """return ...

  7. VMware虚拟磁盘修复

    最近VMware虚拟机老是断掉提示无法完成同步,后来提示虚拟磁盘需要修复,经过一番查询,找到了相关检查与修复口令,先记录如下. vmware-vdiskmanager -R “PATH” 说明: PA ...

  8. 初学做uniapp项目过程梳理的一些记录

    1.uniapp不显示h5头部 第一种写法: { "path" : "pages/yunshi/yunshi", "style" : { & ...

  9. Springboot - 更优雅的方式请求发 HTTP 请求

    参考:https://www.cnblogs.com/javazhiyin/p/9851775.html RestTemplate 是 Spring 提供的用于访问Rest 服务的客户端RestTem ...

  10. SAM(后缀自动机)总结

    “写sam是肯定会去写的,这样才学的了字符串,后缀数组又不会用 >ω<, sam套上数据结构的感觉就像回家一样! 里面又能剖分又能线段树合并,调试又好调,我爱死这种写法了 !qwq” SA ...