forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebScrapper.swift
More file actions
161 lines (143 loc) · 4.99 KB
/
Copy pathWebScrapper.swift
File metadata and controls
161 lines (143 loc) · 4.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import Foundation
import SwiftSoup
import WebKit
@MainActor
public final class WebScrapper {
final class NavigationDelegate: NSObject, WKNavigationDelegate {
weak var scrapper: WebScrapper?
public nonisolated func webView(_ webView: WKWebView, didFinish _: WKNavigation!) {
Task { @MainActor in
let scrollToBottomScript = "window.scrollTo(0, document.body.scrollHeight);"
_ = try? await webView.evaluateJavaScript(scrollToBottomScript)
self.scrapper?.webViewDidFinishLoading = true
}
}
public nonisolated func webView(
_: WKWebView,
didFail _: WKNavigation!,
withError error: Error
) {
Task { @MainActor in
self.scrapper?.navigationError = error
self.scrapper?.webViewDidFinishLoading = true
}
}
}
public var webView: WKWebView
var webViewDidFinishLoading = false
var navigationError: (any Error)?
let navigationDelegate: NavigationDelegate = .init()
enum WebScrapperError: Error {
case retry
}
public init() async {
let jsonRuleList = ###"""
[
{
"trigger": {
"url-filter": ".*",
"resource-type": ["font"]
},
"action": {
"type": "block"
}
},
{
"trigger": {
"url-filter": ".*",
"resource-type": ["image"]
},
"action": {
"type": "block"
}
},
{
"trigger": {
"url-filter": ".*",
"resource-type": ["media"]
},
"action": {
"type": "block"
}
}
]
"""###
let list = try? await WKContentRuleListStore.default().compileContentRuleList(
forIdentifier: "web-scrapping",
encodedContentRuleList: jsonRuleList
)
let configuration = WKWebViewConfiguration()
if let list {
configuration.userContentController.add(list)
}
configuration.allowsAirPlayForMediaPlayback = false
configuration.mediaTypesRequiringUserActionForPlayback = .all
configuration.defaultWebpagePreferences.preferredContentMode = .desktop
configuration.defaultWebpagePreferences.allowsContentJavaScript = true
configuration.websiteDataStore = .nonPersistent()
configuration.applicationNameForUserAgent =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0.1 Safari/605.1.15"
if #available(iOS 17.0, macOS 14.0, *) {
configuration.allowsInlinePredictions = false
}
// The web page need the web view to have a size to load correctly.
let webView = WKWebView(
frame: .init(x: 0, y: 0, width: 800, height: 5000),
configuration: configuration
)
self.webView = webView
navigationDelegate.scrapper = self
webView.navigationDelegate = navigationDelegate
}
public func fetch(
url: URL,
validate: @escaping (SwiftSoup.Document) -> Bool = { _ in true },
timeout: TimeInterval = 15,
retryLimit: Int = 50
) async throws -> String {
webViewDidFinishLoading = false
navigationError = nil
var retryCount = 0
_ = webView.load(.init(url: url))
while !webViewDidFinishLoading {
try await Task.sleep(nanoseconds: 10_000_000)
}
let deadline = Date().addingTimeInterval(timeout)
if let navigationError { throw navigationError }
while retryCount < retryLimit, Date() < deadline {
if let html = try? await getHTML(), !html.isEmpty,
let document = try? SwiftSoup.parse(html, url.path),
validate(document)
{
return html
}
retryCount += 1
try await Task.sleep(nanoseconds: 100_000_000)
}
enum Error: Swift.Error, LocalizedError {
case failToValidate
var errorDescription: String? {
switch self {
case .failToValidate:
return "Failed to validate the HTML content within the given timeout and retry limit."
}
}
}
throw Error.failToValidate
}
func getHTML() async throws -> String {
do {
let isReady = try await webView.evaluateJavaScript(checkIfReady) as? Bool ?? false
if !isReady { throw WebScrapperError.retry }
return try await webView.evaluateJavaScript(getHTMLText) as? String ?? ""
} catch {
throw WebScrapperError.retry
}
}
}
private let getHTMLText = """
document.documentElement.outerHTML;
"""
private let checkIfReady = """
document.readyState === "ready" || document.readyState === "complete";
"""