【问题标题】:Swift html parse , find , manipolate and export [closed]Swift html 解析、查找、操作和导出 [关闭]
【发布时间】:2016-12-29 18:05:34
【问题描述】:

我有一个复杂的 HTML,我想解析、查找和操作一些元素。

有人可以说明如何处理这个示例 HTML 吗?

"<!DOCTYPE html>" +
"<html>" +
"<head>" +
"<title>Page Title</title>" +
"</head>" +
"<body>" +
"<h1>This is a Heading</h1>" +
"<p class='paragraph'>This is a paragraph.</p>" +
"<p class='paragraph'>This is a paragraph 2.</p>" +
"</body>" +
"</html>";

【问题讨论】:

    标签: html ios css swift parsing


    【解决方案1】:

    使用SwiftSoup 是一个简单的方法来处理您的发现,这是一个用于处理真实 HTML 的 Swift 库。

    https://github.com/scinfu/SwiftSoup

    这里是一个示例代码:

    do{
                let html = "<!DOCTYPE html>" +
                    "<html>" +
                    "<head>" +
                    "<title>Page Title</title>" +
                    "</head>" +
                    "<body>" +
                    "<h1>This is a Heading</h1>" +
                    "<p class='paragraph'>This is a paragraph.</p>" +
                    "<p class='paragraph'>This is a paragraph 2.</p>" +
                    "</body>" +
                "</html>";
    
                let doc: Document = try SwiftSoup.parse(html)
                let els: Elements = try doc.getElementsByClass("paragraph")
                let el: Element? = els.first()//get first element
                print(try "\(el?.text())")//This is a paragraph.
                try el?.text("New paragraph")
                print(try "\(el?.text())")//New paragraph
    
    
                //add new element
                let newNode: Element =  Element(try Tag.valueOf("em"), "")
                try newNode.appendText("four")
                try doc.body()?.appendChild(newNode)
    
                //add html
                try doc.body()?.append("<p>new html</p>")
    
                print(try doc.html())
            }catch Exception.Error(let type, let message)
            {
                print("")
            }catch{
                print("")
            }
    

    这里是新的 HTML:

    <!doctype html>
    <html>
     <head>
      <title>Page Title</title>
     </head>
     <body>
      <h1>This is a Heading</h1>
      <p class="paragraph">New paragraph</p>
      <p class="paragraph">This is a paragraph 2.</p>
      <em>four</em>
      <p>new html</p>
     </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-23
      • 2010-09-19
      • 1970-01-01
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      相关资源
      最近更新 更多