You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从已加载的UIWebView获取无冗余空格的有效HTML?

Fixing Clean, Valid HTML Extraction from UIWebView

Hey there! I’ve dealt with this exact frustration when pulling HTML from UIWebView—those extra spaces, line breaks, and random cruft can totally break the validity of the markup. Let’s go through a couple of solid approaches to get you clean, usable HTML:

1. Refine Your JavaScript Evaluation

First, let’s tweak the JS you’re running to strip out redundant whitespace right at the source. Instead of just grabbing outerHTML or using XMLSerializer, add regex to collapse excess whitespace and trim edges:

let cleanHTMLJS = """
document.documentElement.outerHTML
  .replace(/\\s+/g, ' ')
  .trim()
"""

if let rawHTML = self.webView.stringByEvaluatingJavaScript(from: cleanHTMLJS) {
    // rawHTML now has collapsed spaces and no leading/trailing whitespace
    // Send this cleaned HTML to your server
}

What this does:

  • replace(/\\s+/g, ' '): Collapses any sequence of whitespace (spaces, tabs, newlines) into a single space—this keeps necessary spacing between elements but removes the messy excess.
  • .trim(): Gets rid of any leading or trailing whitespace that might be hanging around the entire document.

If you prefer using XMLSerializer (which can sometimes handle more complex documents better), adjust it the same way:

let serializerJS = """
new XMLSerializer().serializeToString(document)
  .replace(/\\s+/g, ' ')
  .trim()
"""

2. Post-Processing with iOS String/Regex Tools

If the JS approach still leaves some stray characters, you can clean things up further on the iOS side using Swift’s built-in string methods or regex:

guard let rawHTML = self.webView.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML") else {
    return
}

// Collapse multiple whitespaces to a single space
let cleanedHTML = rawHTML.replacingOccurrences(
    of: "\\s+",
    with: " ",
    options: .regularExpression
)

// Optional: Remove HTML comments if they're causing issues
let noCommentsHTML = cleanedHTML.replacingOccurrences(
    of: "<!--[\\s\\S]*?-->",
    with: "",
    options: .regularExpression
)

let finalValidHTML = noCommentsHTML.trimmingCharacters(in: .whitespacesAndNewlines)

This gives you extra control—you can even add custom regex rules to strip out specific invalid characters if you encounter them.

Quick Side Note

Just a heads-up: UIWebView has been deprecated since iOS 12. If you have the bandwidth, migrating to WKWebView will give you better performance and more robust JS evaluation APIs (like the async evaluateJavaScript(_:completionHandler:)). But the above fixes work perfectly for UIWebView if you’re stuck with it for now.

内容的提问来源于stack exchange,提问作者Muhammad Ahmed Baig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:26:10