python多线程采集图片
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多线程采集图片的更多相关文章
- Python多线程采集百度相关搜索关键词
百度相关搜索关键词抓取,读取txt关键词,导出txt关键词 #百度相关搜索关键词抓取,读取txt关键词,导出txt关键词 # -*- coding=utf-8 -*- import request ...
- python多线程采集
import requests import json import threading Default_Header = { #具体请求头自己去弄 } _session=requests.sessi ...
- python多线程批量下载远程图片
python多线程使用场景:多线程采集, 以及性能测试等 . 数据库驱动类-简单封装下 mysqlDriver.py #!/usr/bin/python3 #-*- coding: utf-8 -*- ...
- Python查询MySQL进行远程采集图片实例
这是四五年以前做小说站采集图片时写过唯一一次 Python 代码 #!/usr/bin/python #-*-coding:utf-8-*- import MySQLdb, os, socket, t ...
- python多线程爬虫+批量下载斗图啦图片项目(关注、持续更新)
python多线程爬虫项目() 爬取目标:斗图啦(起始url:http://www.doutula.com/photo/list/?page=1) 爬取内容:斗图啦全网图片 使用工具:requests ...
- Python 多线程教程:并发与并行
转载于: https://my.oschina.net/leejun2005/blog/398826 在批评Python的讨论中,常常说起Python多线程是多么的难用.还有人对 global int ...
- 使用file_get_content系列函数和使用curl系列函数采集图片的性能对比
由于公司的一个汽车网站的后台的汽车内容都是主要是来自与汽车之家的,编辑的同事们必须天天手动去对着汽车之家来添加汽车,实在是太蛋疼了.于是乎,为了改变这种状况,作为一个开发码农,我的任务就来了...那就 ...
- Python多线程Selenium跨浏览器测试
前言 在web测试中,不可避免的一个测试就是浏览器兼容性测试,在没有自动化测试前,我们总是苦逼的在一台或多台机器上安装N种浏览器,然后手工在不同的浏览器上验证主业务流程和关键功能模块功能,以检测不同浏 ...
- 13行代码实现:Python实时视频采集(附源码)
一.前言 本文是<人脸识别完整项目实战>系列博文第3部分:程序设计篇(Python版),第1节<Python实时视频采集程序设计>,本章内容系统介绍:基于Python+open ...
随机推荐
- eclipse中使用maven update project功能后,默认又回到了jre 1.5的解决方案
在maven项目中的pom.xml中添加以下节点,进行jre版本的配置,配置完后再进行项目更新后,并不会自动切换到jre1.5 添加在pom的url标签后面 <build> ...
- ubuntu磁盘分配和挂载
Linux(ubuntu)可以把分区作为挂载点,常用的几个挂载点.作用及一般应该分配的磁盘空间如下表所示: Markdown Extra 表格语法: 挂载点(目录) 建议大小 格式 作用 / 20G左 ...
- Educational Codeforces Round 73
唉,又是掉分的一场比赛... A. 2048 Game 题意:给出一个数组,问能不能通过一系列操作(将数组中的两个数相加变成另一个数),使得数组中包含2048,数组中的数全是2的指数,可以则输出YES ...
- 7,请描述下cookies,sessionStorage和localStorage的区别
7,请描述下cookies,sessionStorage和localStorage的区别 首先,cookie是网站为了标识用户身份而储存在用户本地终端(client side,百科: 本地终端指与计算 ...
- Hadoop重新格式namenode后无法启动datanode的问题
这个很简单的哇~ 格式化namenode之后就会给namenode的ClusterId重新生成,导致与datanode中的ClusterId不一致而无法启动datanode 解决方法: 进入hadoo ...
- Python解决RSA加密
最近爬个网站需要用发现密码是通过RSA加密的,因此找网上python加密例子,发现都没有一个比较完整的demo so,自己写一个吧~ 首先,安装相应的库: 1. pyCrypto : pip inst ...
- 安卓之图像视图ImageView
一.有关属性说明 (1)scaleType:指定图形的拉伸类型,默认是fitCenter:拉伸类型的取值如下: (2)src:指定图形来源,src图形按照scaleType拉伸:背景图不按scaleT ...
- Fluent_Python_Part4面向对象,08-ob-ref,对象引用、可变性和垃圾回收
第四部分第8章,对象引用.可变性和垃圾回收 1. 创建对象之后才会把变量分配给对象 变量是对象的标注,是对象的别名,是对象的引用,并不是对象存储的地方. 例子1. 证明赋值语句的右边先执行 class ...
- python的matplotlib的热门可视化动图
1.图 2.代码 import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import matplot ...
- Codeforces Round #618 (Div. 2)A. Non-zero
Guy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,an ]. In one step they can add 11 to ...