Reputation: 6713
I'm trying to pull out information from some source code.
view-source:http://www.championcounter.com/mordekaiser
There are multiple occurrences of something like this:
alt="Mordekaiser counters Talon">
alt="Mordekaiser counters Akali">
I'm looking to pull out the "Talon" and "Akali".
I can currently get whoever's the first person in the list, in this case Talon with:
let sourceArray = sourcecode.components(separatedBy: "alt="Mordekaiser counters")
let sourceArray2 = sourceArray[1].components(separatedBy: ""/>div>")
let champ = sourceArray2[0]
My issue is that this then obviously splits up the source code like
Everything before Talon-------Talon-------Everything after Talon
and I'm just grabbing Talon.
How would I then go on to sift through the source code to get the next items that all are surrounded by the same "separatedBy" code?
Upvotes: 0
Views: 54
Reputation: 535944
You're going to have a much easier time if you first use a regular expression to pull out all the "counters" info, like this (warning, this is Swift 2.2, not Swift 3):
let pattern = "alt=\".*?\""
let s = // source of the page
let exp = try! NSRegularExpression(pattern: pattern, options: [])
let res = exp.matchesInString(s, options: [], range: NSMakeRange(0,s.utf16.count))
for ares in res {
print((s as NSString).substringWithRange(ares.range))
}
var alts = res.map {ares in (s as NSString).substringWithRange(ares.range)}
alts = alts.filter {($0 as NSString).containsString(" counters ")}
alts = alts.map {($0 as NSString).substringWithRange(NSMakeRange(5,$0.utf16.count-6))}
Result is an array of strings:
["Cassiopeia counters Mordekaiser", "Lux counters Mordekaiser", "Yorick counters Mordekaiser", "Xerath counters Mordekaiser", "Malzahar counters Mordekaiser", "Illaoi counters Mordekaiser", "Mordekaiser counters Talon", "Mordekaiser counters Malphite", "Mordekaiser counters Akali", "Mordekaiser counters Diana", "Mordekaiser counters Kassadin", "Mordekaiser counters Gragas"]
Now you've got something you can start parsing for pairs in a useful way.
Upvotes: 1