从HTML中提取JavaScript代码中的变量值

时间:2019-01-17 07:24:01

标签: javascript html ios swift regex

我正在使用称为Kanna的解析库来获取网页的HTML代码。基本上,精简版看起来像这样。

<!DOCTYPE html>
<html lang="en" class="no-js not-logged-in client-root">

<head>
    <meta charset="utf-8">
</head>

<body>

    <script type="text/javascript">
        window._sharedData = { 
            // Some JSON
        };
    </script>

    <script type="text/javascript">
        // Javascript code
    </script>

    <script type="text/javascript">
        // More Javascript code
    </script>

</body>

</html>

script中有多个body标签。我想访问一个名为window._sharedData的变量,并将其值提取为JSON字典。

我尝试使用正则表达式,但返回nil。我的模式可能有问题吗?

if let doc = try? HTML(url: mixURL, encoding: .utf8), let body = doc.body, let htmlText = body.text {  

    let range = NSRange(location: 0, length: htmlText.utf8.count)
    let regex = try! NSRegularExpression(pattern: "/<script type=\"text/javascript\">window._sharedData = (.*)</script>/")
    let s = regex.firstMatch(in: htmlText, options: [], range: range)
    print(s)

}

或者有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

这里是:

import Foundation
import Kanna

let htmlString = "<!DOCTYPE html><html lang=\"en\" class=\"no-js not-logged-in client-root\"><head> <meta charset=\"utf-8\"></head><body> <script type=\"text/javascript\"> window._sharedData = { \"string\": \"Hello World\" }; </script> <script type=\"text/javascript\"> </script> <script type=\"text/javascript\"> </script></body></html>"

guard let doc = try? HTML(html: htmlString, encoding: .utf8) else { print("Build DOM error"); exit(0) }

let body = doc.xpath("//script")
            .compactMap { $0.text }
            .filter { $0.contains("window._sharedData") }
            .map { $0.replacingOccurrences(of: " window._sharedData = ", with: "") }
            .map { $0.dropLast(2) }
            .first

print("body: ", body) 
// body:  Optional("{ \"string\": \"Hello World\" }")

之后,您可以检查身体是否未准备就绪