Skip to content

Instantly share code, notes, and snippets.

@artyom-ivanov
Last active May 23, 2024 09:44
Show Gist options
  • Save artyom-ivanov/a73175a7e80545700539603a20cdffd5 to your computer and use it in GitHub Desktop.
Save artyom-ivanov/a73175a7e80545700539603a20cdffd5 to your computer and use it in GitHub Desktop.
Parse video ids from youtube without API on Swift
func getVideosFor(query: String) -> Set<String> {
let safeQuery = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let myURLString = "https://www.youtube.com/results?search_query=\(safeQuery)"
guard let myURL = URL(string: myURLString) else {
print("Error: \(myURLString) doesn't seem to be a valid URL")
return Set()
}
do {
let plainHTMLString = try String(contentsOf: myURL, encoding: .utf8).replacingOccurrences(of: #"\x22"#, with: #"""#)
let pattern = #""videoId":"([^\"]+)""#
let regex = try! NSRegularExpression(pattern: pattern)
var parsedVideoIds = Set<String>()
let stringRange = NSRange(location: 0, length: plainHTMLString.utf16.count)
let matches = regex.matches(in: plainHTMLString, range: stringRange)
for match in matches {
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (plainHTMLString as NSString).substring(with: nsRange)
parsedVideoIds.insert(string)
}
}
return parsedVideoIds
} catch let error {
print("Error: \(error)")
return Set()
}
}
let ronaldoVideos = getVideosFor(query: "ronaldo")
// ["dbp91G9EA8U", "cpcRaOQjTdI", "Gsq1QhVDXyY", "G29kSbMYNHw", "KJd3405M3Qw", "8-5n0L2uLDg", "toxp8YHn3GY", "x_fc_HxcL-o", "ayMJxT13pgY", "y89Npmx-zG0", "OUKGsb8CpF8", "-MmdxqbrWWU", "n0un__Wiqww", "inwTxR6d6W0", "AmHsd9NG_fs", "kg4VVXhfO4g", "7BSoyT4V_S4", "z7xI58dFZjI", "Y1P6_vOzAzA", "L6Uftuyqixg", "cSdMZehoiiU", "gqVc2kgZths", "-_EVfrXqkEo"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment