我正试图使用Kanna将html解析到我的快速项目中,我使用了这个What is the best practice to parse html in swift?作为指南。
下面是我用来解析html的代码:
if let doc = Kanna.HTML(html: myHTMLString, encoding: String.Encoding.utf8) {
var bodyNode = doc.body
if let inputNodes = bodyNode?.xpath("//a/@href[ends-with(.,'.txt')]") {
for node in inputNodes {
print(node.content)
}
}
}现在我没有这方面的经验,但我相信我必须改变.xpath("//a/@href[ends-with(.,'.txt')]"),以获得我需要的具体信息。
这是html im试图解析:
视图-来源:compounds
我想要的是标题:“锑酸铝”和化学式:"AlSb“。

有人能告诉我用.xpath(...)写什么吗,或者向我解释一下它是如何工作的?
发布于 2017-03-27 17:30:40
Swift 3
使用循环获取所有项
for item in doc.xpath("//div[@class='mw-content-ltr']/ul/li") {
print(item.at_xpath("a")?["title"])
print(item.text) // this returns the whole text, you may need further actions here
}或访问特定项
print(doc.xpath("//div[@class='mw-content-ltr']/ul/li")[0].at_xpath("a")?["title"])
print(doc.xpath("//div[@class='mw-content-ltr']/ul/li")[0].text)您可以查看xpath教程和文档以获得更多信息。
https://stackoverflow.com/questions/40748762
复制相似问题