안녕하세요. 이번시간에는 네이버 OPEN API를 사용하여 블로그에 사람들이 등록한 MP3 또는 WMA형식의 음악파일의 다운로드 주소를 추출하는 기능을 구현 해보겠습니다. 이번에 구현할 Sample Application은 아래와 같습니다. 간단하게 Keyword를 입력받고, Keyword에 해당하는 음악파일을 다운로드 할 수 있는 URL을 출력해 줍니다.
아래는 소스코드입니다.
public static class Extractor
{
const String OPENAPIKEY = "87b0c706f01ebc494df5ea894a6c0aa5";
public static List Search(string Keyword)
{
XmlDocument Doc = new XmlDocument();
Doc.Load("http://openapi.naver.com/search?key="
+ OPENAPIKEY
+ "&display=5&start=1&target=blog&sort=sim&query=" + Keyword);
List MusicList = new List();
XmlNodeList LinkList = Doc.GetElementsByTagName("link");
String TempItem;
foreach (XmlNode LinkItem in LinkList)
{
TempItem = ExtractMusic(LinkItem.InnerText);
if (String.IsNullOrEmpty(TempItem) == false)
MusicList.Add(TempItem);
}
return MusicList;
}
private static String ExtractMusic(String URL)
{
if (URL.StartsWith("http://blog.naver.com/") == false)
return null;
WebClient Downloader = new WebClient();
String UserID = URL.Substring(22, URL.IndexOf("?") - 22);
String PostNumber = URL.Substring(URL.LastIndexOf("=") + 1);
String PritPageURL = "http://blog.naver.com/PostPrint.nhn?blogId="
+ UserID
+ "&logNo=" + PostNumber;
String Source = Downloader.DownloadString(PritPageURL);
int Start, End;
String TempItem;
End = Source.IndexOf(".wma", StringComparison.CurrentCultureIgnoreCase) + 4;
if (End < 4)
End = Source.IndexOf(".mp3", StringComparison.CurrentCultureIgnoreCase) + 4;
Start = Source.LastIndexOf("http://", End);
if (End < 4) return null;
TempItem = Source.Substring(Start, End - Start);
return TempItem;
}
} - Search(String Keyword) 메서드를 이용하여 검색.
- OPEN API Key와 Blog검색 API를 사용하여 해당 Keyword를 가지고 있는 Blog URL검색
- XMLDocument Class를 사용하여 해당 Link만 추출
- ExtractMusic(String URL)를 사용하여 음원 추출
- Blog Print Page를 사용하여 게시물 Source코드만 추출
- WebClient.DownloadString 메서드를 사용하여 소스코드 다운로드
- URL추출
Console.WriteLine("==========================");
Console.WriteLine(" NAVER MUSIC EXTRACTOR");
Console.WriteLine("==========================");
String Keyword = "";
do
{
Console.Write("Keyword : ");
Keyword = Console.ReadLine();
if (String.IsNullOrEmpty(Keyword) == true) continue;
List Result = Extractor.Search(Keyword);
Console.WriteLine("==========================");
foreach (String Item in Result)
{
Console.WriteLine(" - " + Item);
Console.WriteLine("==========================");
}
} while (true); 
