简体   繁体   English

console.log() 没有在间隔内记录到控制台

[英]console.log() not logging to console inside interval

I've looked through numerous post and can't seem to find the answer to my problem.我浏览了很多帖子,似乎找不到我的问题的答案。

I have a console.log expression in my interval.我的间隔中有一个 console.log 表达式。 When the code is ran in the console, it executes flawlessly, but refuses to console.log my string notifying the client sided user that the script is working.当代码在控制台中运行时,它完美地执行,但拒绝控制台记录我的字符串,通知客户端用户脚本正在运行。

Heres my code with notes:这是我的带注释的代码:

  • initialize likes to 0初始化喜欢为0
  • set interval and seconds (in ms)设置间隔和秒数(以毫秒为单位)
  • define like button定义like按钮
  • define next picture button定义下一张图片按钮
  • if there's a likeButton, click likeButton如果有likeButton,点击likeButton
  • add 1 to likes and log to console the string将 1 添加到喜欢并记录以控制台字符串
  • click the arrow to go to new photo单击箭头转到新照片
let likes = 0;

setInterval(() => {
    const likeButton = document.querySelector('svg[aria-label="Like"]');
    const nextButton = document.querySelector('svg[aria-label="Next"]');
    if (likeButton) {
        likeButton.parentNode.parentElement.click()
        likes++;
        console.log(`You've liked ${likes} post(s)`); 
    }
    nextButton.parentElement.parentNode.click();
}, 20000);

From the inspect source of a few posts I've looked at on Instagram, it looks like there are two states to the like button.从我在 Instagram 上看过的几篇帖子的inspect source来看,点赞按钮似乎有两种状态。

  • <svg aria-label="Like" /> when the post has not been liked yet. <svg aria-label="Like" />当帖子还没有被点赞时。
  • <svg aria-label="Unlike" /> when the post has been liked by you already. <svg aria-label="Unlike" />当帖子已被您点赞时。

The problem is that const likeButton = document.querySelector('svg[aria-label="Like"]');问题是const likeButton = document.querySelector('svg[aria-label="Like"]'); is returning the entire element as an object, and isn't a true/false value so if (likeButton) { will never be true but as @Unmitigated pointed out it can be "truthy."将整个元素作为对象返回,并且不是真/假值,因此if (likeButton) {永远不会为真,但正如@Unmitigated 指出的那样,它可能是“真实的”。 To determine if the button has been clicked and to eliminate any "truthy wiggle room" you need to look at the attribute on the likeButton element.要确定按钮是否已被单击并消除任何“真正的摆动空间”,您需要查看likeButton元素上的属性。 You can use getAttribute() for this.为此,您可以使用 getAttribute()。

let likes = 0;

setInterval(() => {
    const likeButton = document.querySelector('svg[aria-label="Like"]');
    const nextButton = document.querySelector('svg[aria-label="Next"]');
    if (likeButton.getAttribute("aria-label") === "Like")) {
        likeButton.parentNode.parentElement.click();
        likes++;
        console.log(`You've liked ${likes} post(s)`); 
    }
    nextButton.parentElement.parentNode.click();
}, 20000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM