我正在尝试<a> some text </a>
从网页中获取 3 个链接的文本,并且正在使用 Swift 方法,该方法使用 javascript 来获取 class/id/html 元素来抓取它。除了,我没有从 html 中获得正确的类或 id。
我尝试使用document.getElementsByClassName/Id
所有类/id 并将其调用为我需要的类,但出现错误:
'document.getElementByClass('col-sm-12 col-md-9')', 'document.getElementByClass' is undefined
我不知道为什么。有人可以指出我解决这个问题的正确方向或指出我的错误吗?
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
//I'm calling all the classes and ids
webView.evaluateJavaScript("document.getElementByClass('col-sm-12 col-md-9').document.getElementById('content-top').getElementsByClassName('item hero-container item-container item-content tag-links')") {(result, error) in
guard error == nil else {
print(error!)
return
}
print(String(describing: result))
}
}
没有getElementByClass
DOM 函数。最接近的匹配将是getElementsByClassName
(注意s
和Name
),但这将接受单个类,并返回一个数组。
你可能想document.querySelectorAll
改用它,你可以直接给它一个完整的 CSS 选择器(所以你需要在类.
和 ids 前加上前缀,并且#
在同一个元素上没有为类留下空间:
document.querySelectorAll('.tag-links a')
如果页面中有一个带有 class 的元素,应该就足够tag-links
了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句