从Swift中的webView获取html内容?

时间:2018-11-29 08:49:46

标签: swift uiwebview

我让webView像图像一样显示内容。我的目的是我想完全打印出字符串Thanh toán thành công,并且我不想获取任何html格式。请帮助我如何处理它。感谢您的帮助!

enter image description here

我的代码:

func webViewDidFinishLoad(_ webView: UIWebView) {
    print("pageDidFinished")
    if let html = webView.stringByEvaluatingJavaScript(from: "document.body.innerHTML") {
        print("html=[\(html)]")
    }
}

输出:

html=[
    <form name="form1" method="post" action="Vnpay_return.aspx?vnp_Amount=1000000&amp;vnp_BankCode=NCB&amp;vnp_BankTranNo=20181129164553&amp;vnp_CardType=ATM&amp;vnp_OrderInfo=Thanh+toan+goi+kham+iCNM&amp;vnp_PayDate=20181129164626&amp;vnp_ResponseCode=00&amp;vnp_TmnCode=MLATEC02&amp;vnp_TransactionNo=13115440&amp;vnp_TxnRef=636791069787342509&amp;vnp_SecureHashType=MD5&amp;vnp_SecureHash=8e346e3b07cae8655972bec0e68f30e0" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTIxMzA2NDI4Ng9kFgICAw9kFgICAQ8WAh4JaW5uZXJodG1sBSRUaGFuaCB0byYjMjI1O24gdGgmIzIyNDtuaCBjJiMyNDQ7bmdkZCNmBqLZpz4DIdi6COyJTTG5SVGH">
</div>

<div>

    <input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="C462C8FC">
</div>
     <div class="container">
            <div class="header clearfix">

                <h3 class="text-muted">Kết quả thanh toán</h3>
            </div>
            <div class="table-responsive">
                 <div id="displayMsg">Thanh toán thành công</div>
            </div> </div>
    </form>

  <script src="../js/jquery.min.js" type="text/javascript"></script>
    <link href="../css/bootstrap.min.css" rel="stylesheet" type="text/css">

]

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式获取div的内部文本:

func webViewDidFinishLoad(_ webView: UIWebView) {

    guard let text = webView.stringByEvaluatingJavaScript(from: "document.getElementById(\"displayMsg\").innerText") else {
        return
    }

    print(text) // Thanh toán thành công
}