2016-12-29 9 views
-2

私は複雑なHTMLを持っており、いくつかの要素を解析し、見つけて操作したいと思っています。スウィフト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>"; 

答えて

0

あなたがSwiftSoupを使用して見つけているものを行うための簡単な方法は、現実世界のHTMLでの作業のためにスウィフトライブラリです。ここで

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>