我正在处理 xpath 脚本,我想这样工作,它会每隔 1 秒继续查找 xpath,当找到元素/xpath 时,它将单击该元素,然后等待 5 秒,然后再次开始 1 秒以继续查找,
<script>
/**
* Specify the element XPath
*/
var xpath = "/html/body/div[1]/a[5]";
/**
* The following lines do not need to be changed
*/
function getElementByXpath(path) {
return document.evaluate(
path,
document,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
).singleNodeValue;
}
/**
* Find an element with the XPath
*/
var element = getElementByXpath(xpath);
/**
* Exit if the element does not exist
*/
if (!element) {
throw new Error("Error: cannot find an element with XPath(" + xpath + ")");
}
/**
* Click the element
*/
element.click();
</script>
我试过setinterval 1000;但它会每隔一秒点击一次元素,当点击完成时,它应该等待 5 秒,然后再点击。
您尝试使用 setInterval
1000
,这意味着 1 秒。添加另一个 setTimeout 等待 5 秒再检查
<script>
/**
* Specify the element XPath
*/
var xpath = "/html/body/div[1]/a[5]";
/**
* The following lines do not need to be changed
*/
function getElementByXpath(path) {
return document.evaluate(
path,
document,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
).singleNodeValue;
}
function clickElement() {
/**
* Find an element with the XPath
*/
var element = getElementByXpath(xpath);
/**
* Exit if the element does not exist
*/
if (!element) {
console.log("Element not found with XPath: " + xpath);
return;
}
/**
* Click the element
*/
element.click();
/**
* Wait for 5 seconds before checking again
*/
setTimeout(function() {
setInterval(clickElement, 1000);
}, 5000);
}
/**
* Start the script by clicking the element
*/
clickElement();
</script>
最好使用
setTimeout
而不是 setInterval
,否则您将需要处理停止计时器的问题。
var RETRY_DELAY = 1000;
var COOLOFF_DELAY = 5000;
function pollElement() {
/**
* Find an element with the XPath
*/
var element = getElementByXpath(xpath);
/**
* If the element doesn't exist, wait RETRY_DELAY then retry
*/
if (!element) {
console.log("Element not found with XPath: " + xpath);
setTimeout(pollElement, RETRY_DELAY);
}
/**
* Click the element
*/
element.click();
/**
* Wait for COOLOFF_DELAY before checking again
*/
setTimeout(pollElement, COOLOFF_DELAY);
}
// Start polling
pollElement();