javascript定时替换多个xpath的a标签链接案例,js代码批量替换网页链接url地址代码
<script>
// 定义要替换的 XPath 和链接的对应关系
const replacements = [
{ xpath: '/html/body/div[2]/nav/div[2]/div[1]/ul/li[6]/ul/li[1]/ul/li[1]/a', link: 'http://baidu.com' },
{ xpath: '/another/xpath/for/another/element', link: 'http://anotherlink.com' }
// 添加更多的替换对象
];
function replaceLinks() {
let allReplaced = true;
for (const replacement of replacements) {
const element = document.evaluate(replacement.xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (!element || element.href!== replacement.link) {
allReplaced = false;
if (element) {
element.href = replacement.link;
}
}
}
if (allReplaced) {
clearInterval(intervalId);
}
}
const intervalId = setInterval(replaceLinks, 100);
</script>