如何在重复的时间间隔内按ClassName交替自动单击2个按钮?

时间:2018-10-27 23:52:06

标签: javascript userscripts tampermonkey

我正在尝试制作一个自动点击器,该按钮在每小时的按钮1和2之间交替显示。
但是我在使用正确的选项单击时在获取具有父级和子级关系的类名时遇到问题。

按钮类似于:

from pandas.io.html import read_html
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get('https://einstein.exchange/contact-us')

WebDriverWait(driver, 20).until(
 EC.presence_of_element_located((By.XPATH, """(//div[@class = 'contact-us'])""")))

BTC = driver.find_element_by_xpath("(//div[@class = 'contact-us'])")
BTC_html = BTC.get_attribute('innerHTML')
print (BTC_html)
driver.close()
with open("OutputEinstein.txt", "w") as text_file:
    print(format(BTC_html), file=text_file)

我尝试使用<button class="trick__btn js-cta" data-door="1">Open</button> <button class="trick__btn js-cta" data-door="2">Open</button> 来获取特定的类名并单击它,但是它不会影响页面:

document.querySelectorAll

1 个答案:

答案 0 :(得分:0)

很多事情:

  1. 您的CSS选择器错误:类需要加.并按如下所示选择属性。
  2. 您需要一种方法来记住最后一个按钮-特别是在页面重新加载时。下面,我使用一个sessionStorage变量。
  3. 可能需要等待按钮加载。一种方法是使用waitForKeyElements()

这是完整的工作脚本,其中显示了该过程:

// ==UserScript==
// @name     _Click Alternate buttons
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// @grant    GM.getValue
// ==/UserScript==
//- The @grant directives are needed to restore the proper sandbox.
/* global $, waitForKeyElements */
/* eslint-disable no-multi-spaces */

waitForKeyElements (".trick__btn.js-cta[data-door='1']", startButtonClicking, true);

function startButtonClicking () {
    clickAlternateButton ();  // Initial. Comment out to wait for 1st click.

    //  5000 = 5 seconds. For 1 hour, use: 3600000.
    setInterval (clickAlternateButton, 5000);
}

function clickAlternateButton () {
    var zButton;

    if (sessionStorage.TM_button_1_WasLastClicked === "true") {
        sessionStorage.TM_button_1_WasLastClicked = false;
        zButton = $(".trick__btn.js-cta[data-door='2']");
    }
    else {
        sessionStorage.TM_button_1_WasLastClicked = true;
        zButton = $(".trick__btn.js-cta[data-door='1']");
    }
    console.log ("Clicking a button", zButton.attr("data-door"), new Date() );
    clickNode (zButton);
}

function clickNode (jNode) {
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}