使用Kanna和Xpath快速报废

Ser*_* Di 1 xpath swift

我有HTML页面,如:

...
// Product 1
<div class="lst_main">
    <a href="link1.html">
    <span> Product 1 name </span>
    <div class="lst_meta">
        <span> Product1 $price</span>
    </dev>
</div>
// Product 2
<div class="lst_main">
</div>
....
// Product N
<div class="lst_main">
</div>
....
Run Code Online (Sandbox Code Playgroud)

我需要获取每个产品的URL,名称和价格.对于这个任务,我使用Kanna lib,这里是我的代码:

let myURLString = "https://url/to/page"
let myURL = URL(string: myURLString)
do {
    let myHTMLString = try String(contentsOf: myURL, encoding: .ascii)
    if let doc = HTML(html: myHTMLString, encoding: .utf8) {
      for product in doc.xpath("//div[@class='lst_main']") {
          print(product.text)
      }
    }
} catch let error {
print("Error: \(error)")
}
Run Code Online (Sandbox Code Playgroud)

使用此代码,我可以获得每个产品.但我无法理解,如何获得每个产品的链接,名称和价格?

Ser*_* Di 5

我找到了解决方案:

for product in doc.xpath("//div[@class='lst_main']") {
      let productURL = product.at_xpath('a')
      print(productURL?["href"])
      let productName = product.at_xpath('span')
      print(productName?.text)
      let productPrice = product.at_xpath('div[@class='lst_meta']/span')
      print(productPrice?.text)
}
Run Code Online (Sandbox Code Playgroud)