从tesco HTML Xcode Swift4中获取配料信息

时间:2018-12-04 23:07:15

标签: html xcode swiftsoup

我正在使用swiftsoup! 我正在尝试复制此信息,以便我可以查看表单配料

<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>

但是由于它不是代码中的第一个P标签,所以我无法访问它……我的代码如下

 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)}

            }


        }

所以我在这里的线

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

需要进行编辑,以便找到另一个P标签,而不是第一个。......我该怎么做?现在代码以.first()结尾!

1 个答案:

答案 0 :(得分:0)

您可以一次获得一个类的所有元素;

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

     for link: Element in els.array() {
       // process them here
     }
  } catch
  {
     print("error")
  }