【发布时间】:2018-06-12 16:23:12
【问题描述】:
假设我想遍历以下 HTML 以进行正则表达式匹配:
<ul class="product_images">
<li>
<a data-style-name="keyword_1">
<img>
</a>
</li>
<li>
<a data-style-name="keyword_2">
<img>
</a>
</li>
</ul>
我可以使用Kanna 之类的解析器和NSRegularExpression 之类的块迭代器方法来计算<li> 的每个实例并返回第一个匹配项的索引,然后我可以使用它来模拟鼠标单击像这样的匹配元素:
WKWebView.evaluateJavaScript("document.getElementsByClassName('product_images')[\(keywordIndex)].click()", completionHandler: nil)
但是使用像$("li:contains('keyword_2')") 这样的jQuery 选择器呢?来自 Python 和 JavaScript,我无法适应 Swift 的语法,我觉得我可以使用 jQuery 选择器来压缩我的函数。大多数 threads 建议使用依赖项,但我想知道是否有办法在 Swift 中本地执行此操作 - 也许是 NSSelectorFromString?也就是说,如果任何更精通该语言的人可以为我指出正确的方向,我将非常感谢您的帮助。下面是我的代码示例。实际上,我无法计算每个 <li> 元素的数量;我想点击包含keyword_2的那个。
片段
// Go to parent of match element and count each <li> element
func findKeyword() {
var keyword = "keyword_2"
var keywordIndex = 0
DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) {
self.browserView.evaluateJavaScript("document.getElementsByTagName('html')[0].innerHTML.toString()", completionHandler: { (html: Any?, error: Error?) in
if let HTML = html as? String {
let doc = try? Kanna.HTML(html: HTML, encoding: String.Encoding.utf8)
for string in (doc?.css("ul[class^='product_images']/li"))! {
if keyword(true, {$0 && string.text!.range(of: $1) != nil}) {
print("Found: " + string.text!)
}
keywordIndex += 1
}
}
})
}
}
【问题讨论】:
-
@LeoDabus 好的,所以我会像这样编辑函数的参数:
func FindKeyword(options: NSRegularExpression),对吗? -
@LeoDabus 知道了。我现在如何解决以下错误:
Cannot call value of non-function type 'String'?
标签: jquery regex swift cocoa nsregularexpression