나영갤에서 그림 받아오기.

orangecrs의 이미지

얼마전 소녀시대 짤방 갤 보고 dc란곳에 가봤더니 그림이 참 많더군요. 그래서 제가 좋아하는 나영씨의 갤에서 사진을 긁어와서 하드에 저장을 할수 있게 python으로 작성해 보았습니다. 원래 Geek Tool이란 OS X에서 돌아가는 툴을 사용하고 있어서 그림 받아온후 이것을 시간에 따라 받아온 그림은 바탕화면 한쪽에 보여 줄수 있게 만들었습니다. 리눅스에서도 그림을 받아와 정기적으로 바탕화면을 갱신할수 있는 툴이 있다면 좋은 장난감이 되지 않을까합니다. 나영갤뿐만 아니라 다른갤에서도 URL만 적당히 바꾸시면 원하시는 갤의 사진을 받아 올수 있을겁니다.
포함된 압축파일에는

recvg.py : 나영갤에서 가장 최근의 포스트를 검색후 가장 최근의 포스트에서 gallSrcNo(아래소스 참고. 기본설정 11000개)의 개수만큼 아래의 검색물 가운데 랜덤하게 하나의 게시물을 선택하고 그 게시물에 다운로드 가능한 그림이 있다면 .jpg로 받아옵니다. 갤러리 특성상 하나의 그림이 아니라 복수의 그림도 있는데 이들은 0.jpg, 1. jpg, 2.jpg, ... 이렇게 받아와서 myimages라는 디렉에 저장합니다. 그리고 myimages/backupPics/에 0.jpg, 1.jpg, 2.jpg... 로 백업을 받습니다. 다음에 다시 recv.py로 받아올때
myimages에 0부터 저장후에 다시 backupPics/에 백업을 하게 되는데 이때는 만약 backupPics/의 디렉에 0부터 시작해서 100.jpg가 백업되어 있다면 새로 받아온 파일은 101..jpg로 저장이 됩니다. 이런식으로 작동이 됩니다.

selpic.py : 이것은 위에 말씀드렸듯이 geek Tool이란 툴로 바탕화면에 그림을 보여주기 위해 만든건데, myimages에 새로 받아온 파일들이 하나가 아니라 말씀드렸듯이 한게시물에서 여러개의 그림을 올리는 경우 하나만 선택하기 아쉬워서, 그들중(0.jpg, 1.jpg,...)에 하나를 랜덤하게 선택해서 'cbg.jpg'라는 이름으로 복사를 하게 됩니다. 바탕화면등의 지정에서 파일이름은 정해져야 해야해서(Geek Tool에서) 스크립트를 만들었습니다. 리눅스에서 바탕화면을 주기적으로 바꿀수 있는 프로그램이나 툴이 있다면 이 스크립트가 도움이 될듯합니다.

올리는 소스 좀 난잡해도 python이라 줌바꿈에 민감해서, 특히나 selpic같은 경우 디버그를 위한 print 남발이 있는데 가능하시면 적당히 삭제후 쓰시기 바랍니다.;;;

그리고 제 블로그 열었습니다. 리눅스에 관한 사이트는 아니고 OS X에 관한 사이트입니다. 많이들 들러 주시길... 블로그가 osxinside인데 만들고 글 몇개 써놓고 보니 dc랑 뉘앙스가 연결이되니..;; 블로그에 이 스크립트와 Geek Tool적용된 화면 보실수 있습니다.

http://osxinside.tistory.com/

아래는 소스입니다. 소스 Copy&Paste 보다 첨부파일 쓰세요.
recvg.py ::

#!/usr/bin/python
 
import re
import urllib
import random
import os
import glob
 
gallUrlPost = 'http://gall.dcinside.com/list.php?id=nayoung&no='     <span> ### 다른갤 선택시 적당히 찾아보시고 바꿔주세요.</span>
gallUrl = gallUrlPost[0:-4]
gallSrcNo = 11000          <span> ### 최근 게시물로부터의 몇개 아래까지의 DB검색을 의미합니다. 나영갤에 포스트된 글이 원래 많아서 11000 이니깐 다른갤로 수정시 적당히 변경하세요. </span>  
saveDir = "/Users/purewater/Documents/Pictures/myimages/"           <span> ### 받아올 이미지 저장되는 디렉토리입니다. "myimages"는 없으면 자동으로 생성하는데 상위 디랙토리는 생성되어 있어야 합니다.</span>
print ""
print '[[[ Stats for Getting the Pics from Gallery ]]]'
print 'Gallery Url : ',gallUrl
print 'Checking saveDir...'
tmpDir = os.path.split(saveDir)
rlsavDir = tmpDir[0]
if os.path.isdir(saveDir):
       print rlsavDir, "aleady exist."
else:
       print rlsavDir, "does not exist."
       print "Creating saveDir"
       om = os.mkdir(saveDir)
       if os.path.isdir(saveDir):
	  print "SaveDir was created successfully."
       else:
          print "Fail to create saveDir"
 
def readRange():
    print 'Connect to Server...'
    #f = urllib.urlopen(gallUrl)
    try:
       f = urllib.urlopen(gallUrl)
    except:
       print "Can not connect Server. Check Network..."
       return 0
       #break
    print "Connected. ranging..."
    html = f.read()
    parserToFind1 = '>\d+\d</span>'
    parserToFind2 = '<a href="/list.php\?id=nayoung&no=\d+\d&page'
    #parserToFind3 = '/> <a href="/list.php?id=nayoung&no='
    parserFound = re.findall(parserToFind1, html)
    parserFound2 = re.findall(parserToFind2, html)
    realDBnum = parserFound2[6][33:38]
    #print html
    maxNum = parserFound[0][1:6]    
    #print parserFound[0]
    subNum1 = int(maxNum)
    print 'Most recent thread No.', subNum1
    print "Real DB No:",realDBnum
    #print 'maxNumber :', subNum1,',max realDBnum :', realDBnum
    print 'max realDBnum :', realDBnum
    realDBnum2 = int(realDBnum) - gallSrcNo
    subNum2 = subNum1 - gallSrcNo
    #print 'minNumber :', subNum2,',min realDBnum :', realDBnum2
    print 'min realDBnum :', realDBnum2
    print "Drawing in range..."
    extNo = random.randint(realDBnum2,int(realDBnum))
    print 'Adopted random posting number :: ', extNo
    return extNo
 
def bigOne(bigOne,tmpBigone):
    if tmpBigone > bigOne:
       bigOne = tmpBigOne
    else:
       bigOne = bigOne
       return bigOne
 
def calcDirSize(arg, dir, files):
    for file in files:
        stats = os.stat(os.path.join(dir, file))
        size = stats[6]
	#print arg
        arg.append(size)
 
def getDirSize(dir):
    sizes = []
    os.path.walk(dir, calcDirSize, sizes)
    total = 0								
    for size in sizes:					
	total = total + size
    #print total
    return float(total)
 
def backupPics(inputBackfile):
	backupDir = saveDir+"backupPics/"
	#print "backupDir is", backupDir
	if os.path.isdir(backupDir):
	   null = 0	
	   #print backupDir,"aleady exist."
	else:
	   print backupDir, "does not exist."
	   print "Creating saveDir"
	   try:
              om = os.mkdir(backupDir)
           except:
              print "mkdir IOError."
           if os.path.isdir(saveDir):
              print "backupDir was created successfully."
	   else:
	      print "Fail to create backupDir"
 
        fileList = glob.glob(backupDir+'[0-9]*.jpg')
        flSize = len(fileList)
	#print "flSize :",flSize
	bigOne = 0
        for name in fileList:	
	    srcName = os.path.split(name)
	    dirName = srcName[0]
	    fileName = srcName[1]
	    fullFileName = os.path.splitext(fileName)
	    onlyFileName = fullFileName[0]
	    extName = fullFileName[1]
	    #print "filename :",fileName,"onlyFileName :",onlyFileName
	    #print str(onlyFileName)
	    pF = re.search('\D*\d*\D', onlyFileName)
	    #print "PF is",str(pF)
	    if pF:
	       #print "pF is Exist"
	       null = 0
	    else:
	       #print "pF is not Exist"
	       tmpBigone = int(onlyFileName)
 
               if tmpBigone > bigOne:
	          bigOne = tmpBigone
               else:
	          bigOne = bigOne
 
            #print "The BIG one is",bigOne
 
	lNumdet = bigOne + 1
	#print "LNumdet",lNumdet
	#inputFile = backupDir + str(lNumdet)+".jpg"
        srcfile = open(inputBackfile, 'r')
	readLines = srcfile.readlines()
	#print inputFile
	srcName = os.path.split(inputBackfile)
	dirName = srcName[0]
	fileName = srcName[1]
        onlyFileName = os.path.splitext(inputBackfile)
        extName = onlyFileName[1]
	#print dirName
	#print extName
	outputBackfile = backupDir + str(lNumdet)+".jpg"
        #print outputBackfile
	trgfile = open(outputBackfile, 'w')
	for eachLine in readLines:
           trgfile.write(eachLine)
 
	return (flSize,backupDir)
 
 
while 1:
	fileNo = 0
	no = readRange()
	if no == 0:
		print "Quit..."
		break
	else:
		print 'Get post DB No :',no
	#print html
	#no = 39302
	url = gallUrlPost + str(no)
	print "Connecting..."
	try:
	   f = urllib.urlopen(url)
	except:
	   print "Can not connect Server. Check Network..."
	print "Connected. Analyzing thread..."
	html = f.read()
	if 'download.php' not in html:
		print 'Thread', no, 'does not contain any downloadable picture..'
		print "Re-drawing..."
		continue
	else:
		imageUrlList = re.findall("http://image.dcinside.com/download.php[^']+", html)
		print "Reading complete."
		print 'The number of downloaded pics :', len(imageUrlList)
        #print '_______________________________________________'
        #print imageUrlList
        #print '-----------------------------------------------'
        for url in imageUrlList:
	        #print fileNo
	        contents = urllib.urlopen(url).read()
	        file(saveDir+str(fileNo)+'.jpg', 'w').write(contents)
	        iBfile = saveDir+str(fileNo)+'.jpg'
		retValue = backupPics(iBfile)
		ret = bigOne(retValue[0],0)
		#print "retValue :",retValue[0]
		fileNo = fileNo + 1
	totalDirsize = getDirSize(retValue[1])
	#print retValue[1]
	print fileNo,'files backuped. The total number of backup files is',ret+1,'(',round(totalDirsize/1048567,2),'MB)'
	print 'Done...'
	break
 

selpic.py

#!/usr/bin/python
 
import glob
import os
import random
 
saveDir = "/Users/purewater/Documents/Pictures/myimages/"    <span>### recvg.py 가 받아온 파일들이 저장된 디렉토리입니다. recvg.py의 경로와 일치해야 합니다.</span>
fileList = glob.glob(saveDir+"*.jpg")
flSize = len(fileList)
 
print '[[[ Current repository stats ]]]'
print 'The number of files in REPOS. :', flSize - 1
for name in fileList:
	#print name
	pfname = os.path.split(name)
	#print pfname[0]
	#print pfname[1]
 
 
def copyFile(inputFile):
    srcfile = open(inputFile, 'r')
    readLines = srcfile.readlines()
    #print inputFile
 
    srcName = os.path.split(inputFile)
    dirName = srcName[0]
    fileName = srcName[1]
    onlyFileName = os.path.splitext(inputFile)
    extName = onlyFileName[1]
    #print dirName
    #print extName
    print fileName,'is copyied to cbg.jpg'
    print 
 
    outputFile = dirName+'/cbg'+extName    
    print 'cbg.jpg path ::'
    print outputFile
    trgfile = open(outputFile, 'w')
    for eachLine in readLines:
	  trgfile.write(eachLine)
 
    srcfile.close()
    trgfile.close()
 
 
if os.path.isfile(saveDir+"cbg.jpg"):
   print "cbg.jpg exists."
   lastNum = flSize -2
else:
   print "cbg.jpg does not exist. "
   lastNum = flSize - 1
 
#print "last::", lastNum
rn = random.randint(0,lastNum)
#print rn
s = saveDir+str(rn)+".jpg"
copyFile(s)

File attachments: 
첨부파일 크기
Package icon Archive.zip3.46 KB
orangecrs의 이미지

자유게시판에 올리려 했는데 강좌에 등록이 되어 있었네요..;;;
---------------------------------------------------
야!...

---------------------------------------------------
야!...

orangecrs의 이미지

나영갤은 인기가 없는 걸까요? 댓글도 없고... 다른갤도 가능한데...
---------------------------------------------------
야!...

---------------------------------------------------
야!...

김일영의 이미지

나영갤에서 싫어할 것 같은데영...

병맛의 이미지

트래픽만 잔뜩 유발하는 다운족은 바로 IP 차단 넣는 게시판이 대부분이죠.

orangecrs의 이미지

selpic.py는 인터넷과 무관하고 recv.py 한번 실행할때 하나의 게시물에 포함된 사진만 다운 받기때문에 생각하시는 것만큼 트래픽이 발생하지 않습니다.
브라우져 열고 갤 들어가서 게시물 하나 클릭 한거랑 대동소이하다는 말이지요. 저같은 경우 바탕화면에서 사용하기 위해 만들었기 때문에
크론으로 한시간마다 한번씩 실행되고 있습니다.
---------------------------------------------------
야!...

---------------------------------------------------
야!...

d3m3vilurr의 이미지

사실 몇년전에도 ajax를 이용한 dc이미지보기 php라던가 하는게 유행했었어요..

galien의 이미지

나영갤은 악플들이 거의 없어서, 직접 눈팅해도 재미있기 때문이 아닐까요;;;;

(상주 눈팅족이 씀)

scred의 이미지

다른 gallery에 대해 적용할 때,
URL을 두 군데 바꾸어 주어야 하는 것 이외에,

maxNum = parserFound[0][1:6]

이 부분에서 6이라는 숫자가 gallery 글 번호에 따라 줄여줄 필요가 있네요.

올려주신 내용은 잘 쓰겠습니다.

리눅스 데스크탑 사용 두달째.

Informatics

orangecrs의 이미지

살펴보니 그렇군요. 갤의 게시물 번호의 자릿수에 의한것으로 maxNum이외에도 있긴한데;;;() 아.... 스파게티... scred님처럼 적당히 고쳐쓰시길...;;; 파이썬 정규식 관련 파서 처리가 오랜만이라... 지금 생각하면 split로 간단히 될걸...;;
그리고 위에 포스팅된 소스가 압축파일로 올린 소스와 다른거였네요.;; 이것 저것 붙이다보니... 이전 소스를 포스팅했군요.;; 업로드한 파일 소스보세요...''

---------------------------------------------------
야!...

---------------------------------------------------
야!...

Gethoper의 이미지

저는 다운은 되는데.. 다운 받은 파일을 보면,, 사이즈가 0 입니다.
-_-;; 접속도 잘하고 다운로드도 잘된것같은데요 ㅡㅡ;;

[[[ Stats for Getting the Pics from Gallery ]]]
Gallery Url :  <a href="http://gall.dcinside.com/list.php?id=nayoung
Checking" rel="nofollow">http://gall.dcinside.com/list.php?id=nayoung
Checking</a> saveDir...
/home/billy/Desktop/DC_NAYOUNG/temp aleady exist.
Connect to Server...
Connected. ranging...
Most recent thread No. 49922
Real DB No: 59419
max realDBnum : 59419
min realDBnum : 48419
Drawing in range...
Adopted random posting number ::  49143
Get post DB No : 49143