【发布时间】:2019-02-07 18:43:35
【问题描述】:
我想使用第三方框架“不”从 html 文档中提取 JSON 字符串。 我正在尝试创建 iOS 框架,我不想在其中使用第三方框架。
示例网址: http://www.nicovideo.jp/watch/sm33786214
在那个html中,有一行:
我需要提取: JSON_String_I_want_to 提取 并将其转换为 JSON 对象。
使用第三方框架“Kanna”,是这样的:
if let doc = Kanna.HTML(html: html, encoding: String.Encoding.utf8) {
if let descNode = doc.css("#js-initial-watch-data[data-api-data]").first {
let dataApiData = descNode["data-api-data"]
if let data = dataApiData?.data(using: .utf8) {
if let json = try? JSON(data: data, options: JSONSerialization.ReadingOptions.mutableContainers) {
我在网上搜索了类似的问题,但无法适用于我的案例:(我需要承认我没有完全遵循正则表达式)
if let html = String(data:data, encoding:.utf8) {
let pattern = "data-api-data=\"(.*?)\".*?>"
let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let matches = regex.matches(in: html, options: [], range: NSMakeRange(0, html.count))
var results: [String] = []
matches.forEach { (match) -> () in
results.append( (html as NSString).substring(with: match.rangeAt(1)) )
}
if let stringJSON = results.first {
let d = stringJSON.data(using: String.Encoding.utf8)
if let json = try? JSONSerialization.jsonObject(with: d!, options: []) as? Any {
// it does not get here...
}
任何从 html 中提取并将其转换为 JSON 的专家?
谢谢。
【问题讨论】:
-
您可以为此使用
WKWebView,它将解析HTML,然后您会向它询问包含json的那个html标签的内容。不过,解决方案有点重。
标签: html json swift nsregularexpression