0

我正在尝试进行网络抓取,因为该网站的作者没有提供 API,但他希望我为该网站做一个应用程序。该网站是关于获取当天的时间表。所以我得到的打印值是这些。

1: 模块 Kevin Street 1: modulesTime line-height: 13px; 字体大小:11px;顶部:0px;高度:200px;显示:块;宽度:25%;左:0%;右:0px;

我想得到'top:'和'px;'之间的值 所以这意味着我正在寻找字符串中间的 0 值。对于我试图将 200 的值保存在变量中的高度也是如此。

这是我拥有的代码,用于获取标题的模块和作为元素样式的 moduleTime。

import Foundation
import SwiftSoup

enum HTMLError: Error {
    case badInnerHTML
}

struct CalendarResponse {

    init(_ innerHTML: Any?) throws {
        guard let htmlString = innerHTML as? String else { throw HTMLError.badInnerHTML }

        let doc = try SwiftSoup.parse(htmlString)
        let modulesTimeAM = try doc.getElementsByClass("wc-cal-event ui-corner-all calSeriesNaN").array()
        let modulesTimePM = try doc.getElementsByClass("wc-cal-event ui-corner-all calBaseSeries").array()
        let modules = try doc.getElementsByClass("wc-time ui-corner-top").array()

        for index in 1...modules.count {
            let module = try modules[index - 1].text()
            print("\(index): module \n", module)
            let moduleTime = index <= modulesTimeAM.count ? try modulesTimeAM[index - 1].attr("style") : try modulesTimePM[index - 1 - modulesTimeAM.count].attr("style")
            print("\(index): modulesTime \n", moduleTime)
        }
    }

}
4

1 回答 1

0

您可以从一个字符串切片到另一个字符串

extension String {

    func slice(from: String, to: String) -> String? {
        return (range(of: from)?.upperBound).flatMap { substringFrom in
            (range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in
                String(self[substringFrom..<substringTo])
            }
        }
    }
}

并将其与

let top = htmlString.slice(from: "top: ", to: "px") // 0 
let height = htmlString.slice(from: "height: ", to: "px") // 200

在您的情况下,可能不是 htmlString 。你会得到的 :)

于 2019-10-01T14:49:41.003 回答