0

我正在使用 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() 结尾!

4

1 回答 1

0

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

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

     for link: Element in els.array() {
       // process them here
     }
  } catch
  {
     print("error")
  }
于 2019-04-14T03:27:34.327 回答