KLDP 노드 번호로 del.icio.us에 등록하기
글쓴이: keizie / 작성시간: 금, 2007/08/03 - 9:51오전
다음 코드를 파일로 저장해서 노드 번호를 인자로 주고 실행하면 그 번호에 해당하는 글을 읽어서 제목과 태그를 분석한 다음 del.icio.us에 저장합니다. 이때 딜리셔스에는 태그에 빈 칸이 없어야 한다는 규칙이 있어서 빈 칸은 모두 없애게 했습니다.
여러 노드를 한 번에 저장하려면 외부 스크립트에서 실행할 때마다 숫자를 부여하면 될 겁니다. 저는 이렇게 했습니다.
for nid in $(cat favorite_sort.txt | grep \^1051 | cut -f2); do python kldp-post.py $nid; done
딜리셔스에서는 API로 접근할 때 적어도 1초 간격은 두라고 하고 있는데, HTML 페이지 해석이 워낙 느리기 때문에 -_-; 굳이 sleep은 안 넣었습니다.
user = 'USERNAME'
passwd = 'PASSWORD'
from BeautifulSoup import BeautifulSoup
import urllib
import sys
import delicious
BASE_URL = "http://kldp.org/node/"
nid = sys.argv[1]
url = BASE_URL + nid
page = urllib.urlopen(url)
soup = BeautifulSoup(page)
description = soup.title.string.encode('utf-8')
tags = [] # 기본 태그가 필요하면 여기에 ['kldpfav','...'] 식으로 넣어주면 됩니다.
for tag in soup.findAll('a',{'rel':'tag'}):
tags.append(tag.renderContents().replace(' ',''))
delicious.login(user,passwd)
delicious.post_URL(url, description, "", ' '.join(tags))여기에는 delicious.py라는 파일이 같이 있어야 동작합니다. 익히 알려진 pydelicious 같은 걸 써봤더니 뭔가 잘 안 되길래 http://notes.natbat.net/2007/03/06/delicioussnaflr/ 에 있는 http://natbat.net/code/python/snafflr/sync.txt 에서 필요한 부분만 잘라다 썼습니다.
import urllib2, urllib, time, datetime
from xml.dom import minidom
from pprint import pprint
def login(delicious_user, delicious_pass):
"""Takes a username and password and logs into delicious"""
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(
None, 'https://api.del.icio.us/', delicious_user, delicious_pass
)
auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
def urlencode(d):
for key, value in d.items():
if isinstance(value, unicode):
d[key] = value.encode('utf-8')
return urllib.urlencode(d)
def post_URL(url, title, notes, tags):
"""function takes a title, url, description and tags and posts to delicious"""
postUrl = urlencode({
'url': url,
'description': title,
'extended': notes,
'tags': tags,
'replace': 'no'
})
return minidom.parseString(urllib2.urlopen('https://api.del.icio.us/v1/posts/add?'+postUrl).read()).getElementsByTagName('result')[0].getAttribute('code')Forums:

