0

I am using swiftsoup! i am trying to copy this info so i can look form ingredients

<p class="product-info-block__content">Sugar, Cocoa Mass, Cocoa        Butter, Dried Skimmed <strong>Milk</strong>, Dried Whey (from <strong>Milk</strong>), Vegetable Fats (Palm, Shea), <strong>Milk</strong> Fat, Emulsifiers (<strong>Soya</strong> Lecithin, E476), Orange Oil, Flavouring, Milk Solids 14 % minimum, Cocoa Solids 25 % minimum, Contains Vegetable Fats in addition to Cocoa Butter</p>

however since its not the first P tag in the code, i can't get access to it... my code looks like this

 let url9 = URL(string: "https://www.tesco.com/groceries/en-GB/products/301638217")!

    let task = URLSession.shared.downloadTask(with: url9) { localURL, urlResponse, error in
        if let localURL = localURL {
            if let string = try? String(contentsOf: localURL) {
              //  print(string)
                //self.srcCode = string
                //print (srcCode)
                print("boom")
                var allergens9 = [String]()
                do{
                    let doc4 : Document = try SwiftSoup.parse(string)
                    print("made doc")
                    let morrisonPTag : Element = try doc4.select("p").first()!
                    print("made pTag")
                    let strongs = try  morrisonPTag.select("strong")
                    for strong in strongs.array(){
                        let text = try strong.text()

                        if !allergens9.contains(text){
                            allergens9.append(text)
                            print("allergen")
                           print(allergens9)
                        }
                    }


                }catch{print(error.localizedDescription)}

            }


        }

so the line that i have here

 let morrisonPTag : Element = try doc4.select("class=product blocks").first()!

needs to be edited so that is finds another P tag, instead of the first one.......how can i do so? right now the code ends in .first()!

1 Answers1

0

You can get all the elements with a class at once;

do { let els: Elements = try doc!.getElementsByClass("product blocks")

     for link: Element in els.array() {
       // process them here
     }
  } catch
  {
     print("error")
  }
john elemans
  • 2,578
  • 2
  • 15
  • 26