gpt4 book ai didi

javascript - 如何等待网站加载元素的 xpath

转载 作者:行者123 更新时间:2023-11-29 20:34:19 25 4
gpt4 key购买 nike

我希望在我的 javascript 程序中能够通过它们的 xpath 开始搜索网页上的某些元素。我想尽可能快地执行此操作,这意味着我想在页面加载后立即找到该元素。

我试图等待网页的 DOM 加载,不幸的是,您此时只能访问 id 而没有 xpath。

目前我正在使用

window.onload = function() {
//start searching for element
}

这非常慢,尤其是对于有大量图片和其他图片的网站,因为它需要等待加载完整的网站

我想知道(如果可能的话)如何只等待元素的 xpath 准备好并在那一刻开始搜索。

最佳答案

window.DOMContentLoaded 时,所有 DOM 元素都已解析并准备好访问事件触发。 load 事件在所有外部资源完成下载后触发。

在下面的代码中,您会注意到 Parsed 出现在控制台中的 Loaded 之前:

window.addEventListener("DOMContentLoaded", function(){
console.log("Parsed");
});

window.addEventListener("load", function(){
console.log("Loaded");
});
<img src="https://cdn.spacetelescope.org/archives/images/large/heic1608a.jpg">

更新:

根据您在下面的评论,我将您的代码放在一起:

window.addEventListener("DOMContentLoaded", function(){
// Invoke your custom mouse event function. You need to determine
// how the element name will be gotten. Here, I am asking the user
// to supply an element name (div, p, h1, span, etc.)
setupMouseEvent(prompt("Enter an element name."));
});

function setupMouseEvent(elementName){
// Locate the first element that matches the name supplied in the parameter
// Don't use .getElementsByName()[0] to get the first match -
// that's very inefficient and uses an outdated API that returns
// a live node list. Also, no quotes or concatenation is used here.
var cb = document.querySelector(elementName);

// The event code below will dispatch a click event for the element
// but if you don't have a click event handler set up for the element
// then you won't be able to react to the event.
cb.addEventListener("click", function(){
console.log(this.nodeName + " was clicked.");
});

// While the following does set up a click mouse event,
// I'm not sure why you are bothering with it. You could just
// call cb.click() to dispatch the existing click event.
var event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});

cb.dispatchEvent(event);
}
<div>Some Element</div>

关于javascript - 如何等待网站加载元素的 xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57168571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com