Trying to scrape all of the titles of a Soundcloud user's likes into a text file with the API

时间:2016-02-12 19:34:15

标签: soundcloud

I can print the title of an individual link if the link is given, but is there any functionality in the API that would allow me to print each song name of a user's repost and likes one by one into a text file?

1 个答案:

答案 0 :(得分:1)

API公开了一个界面来获取用户的喜欢(/favorites端点)。保存到文件部分是API无关的,您必须编写一个程序来解析API调用的内容并将其写入文件。你没有指定一种语言,所以这里是我写的一个小Swift脚本,用于将用户喜欢的曲目保存到文本文件中:

let userId = "10032807" // User you want to get the likes from
let clientId = "[API KEY]" // your API key

guard let url = NSURL(string: "https://api.soundcloud.com/users/\(userId)/favorites?client_id=\(clientId)") else {
    fatalError("bad URL")
}


NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
    do {

        guard let data = data else {
            return
        }

        if let likes = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String : AnyObject]] {

            var likedTracks = [String]()

            for track: [String : AnyObject] in likes {
                if let title = track["title"] as? String {
                    likedTracks.append(title)
                }
            }

            let output = likedTracks.joinWithSeparator("\n")

            do {
                try output.writeToFile("Users/jal/tracks.txt", atomically: true, encoding: NSUTF8StringEncoding)
            } catch {
                fatalError("Error writing to file: \(error)")
            }
        }



    } catch {
        fatalError("Error with web request: \(error)")
    }
}.resume()