Селен иногда не устанавливает флажок иногда - PullRequest
2 голосов
/ 06 февраля 2020

Я новичок в Selenium, поэтому я делаю бота для автоматического заполнения пустяков, чтобы я мог понять этот модуль, и это хорошая практика. Иногда функция .click () не работает.

Я пытался:

  • Используя JavaScript, чтобы нажать
  • Использование WebDriverWait
  • выход из системы и закрытие драйвера и повторное открытие страницы
  • Продолжайте нажимать, пока не будет введен действительный идентификатор флажка (продолжает цикл)
  • Обновление страницы и попытка щелкнуть снова (Java и обычный .click ()
  • с использованием time.sleep (время) вместо ожидания
  • без использования веб-драйвера вообще и просто установкой переменной

Раньше у меня была ошибка устаревшего элемента, но я исправлял ее.

Примечание: он щелкает большую часть времени, но случайно не работает, не ошибка или что-то еще

Импорт:

from selenium import webdriver
from time import *
from data import *
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException
from winsound import *
import os

Часть кода:

def AutoAnswer(self, answers_list, link):
    global i
    if i == 1:
        self.driver.get(link)
    # sends browser to first trivia
    # sets the variable to the current question so that the correct answer can be located through answer lists

self.current_question = (WebDriverWait(self.driver, 120).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="quizContainer"]/div[2]')))).text

#setting variables for boxes and their text values. The text can be corrolated to the button allowing the bot to click the correct answer
#/html//div[@id="quizContainer"]/div[@class="answersContainer"]/div[1]/span[@class="answerBox"]/a[@name="checkboxtag"]

for i in range(0, len(answers_list)):
    if answers_list[i]["question"] == self.current_question:
        self.current_answer = answers_list[i]["answer"]


self.xpath_1  = '//*[@id="quizContainer"]/div[3]/div[1]/span[1]/a'
self.text_1   = ((WebDriverWait(self.driver, 120)).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="quizContainer"]/div[3]/div[1]/span[2]')))).text


self.xpath_2  = '//*[@id="quizContainer"]/div[3]/div[2]/span[1]/a'
self.text_2   = ((WebDriverWait(self.driver, 120)).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="quizContainer"]/div[3]/div[2]/span[2]')))).text


self.xpath_3  = '//*[@id="quizContainer"]/div[3]/div[3]/span[1]/a'
self.text_3   = ((WebDriverWait(self.driver, 120)).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="quizContainer"]/div[3]/div[3]/span[2]')))).text


self.xpath_4  = '//*[@id="quizContainer"]/div[3]/div[4]/span[1]/a'
self.text_4   = ((WebDriverWait(self.driver, 120)).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="quizContainer"]/div[3]/div[4]/span[2]')))).text

while True:
    if self.text_1 == self.current_answer:
        (WebDriverWait(self.driver, 120).until(EC.element_to_be_clickable((By.XPATH, self.xpath_1)))).click()
    if self.text_2 == self.current_answer:
        (WebDriverWait(self.driver, 120).until(EC.element_to_be_clickable((By.XPATH, self.xpath_2)))).click()
    if self.text_3 == self.current_answer:
        (WebDriverWait(self.driver, 120).until(EC.element_to_be_clickable((By.XPATH, self.xpath_3)))).click()
    if self.text_4 == self.current_answer:
        (WebDriverWait(self.driver, 120).until(EC.element_to_be_clickable((By.XPATH, self.xpath_4)))).click()

    if bot.driver.find_elements_by_class_name("largecheckboxselected") != []:
        print("all good")
        break
    else:
        print("problemo re-running")
        if self.text_1 == self.current_answer:
            (WebDriverWait(self.driver, 120).until(EC.element_to_be_clickable((By.XPATH, self.xpath_1)))).click()
        if self.text_2 == self.current_answer:
            (WebDriverWait(self.driver, 120).until(EC.element_to_be_clickable((By.XPATH, self.xpath_2)))).click()
        if self.text_3 == self.current_answer:
            (WebDriverWait(self.driver, 120).until(EC.element_to_be_clickable((By.XPATH, self.xpath_3)))).click()
        if self.text_4 == self.current_answer:
            (WebDriverWait(self.driver, 120).until(EC.element_to_be_clickable((By.XPATH, self.xpath_4)))).click()
# selects and clicks the "Next Question!" button
nextquestion_btn = WebDriverWait(self.driver, 120).until(EC.element_to_be_clickable((By.XPATH,('//*[@id="nextQuestion"]'))))
nextquestion_btn.click()

Запуск кода:

bot = TriviaBot()
for i in range(1, 13):
    print("Run: "+str(i))
    bot.AutoAnswer(american_presidents, "https://www.freekigames.com/american-presidents-trivia")
bot.claimRewards()

data.py

username = "username"
password = "password"
american_presidents = [
    {"question" : "Who was the 1st president of the United States?",
     "answer"   : "George Washington"},
    {"question" : "Who was the 2nd president of the United States?",
     "answer"   : "John Adams"},
    {"question" : "Who was the 3rd president of the United States?",
     "answer"   : "Thomas Jefferson"},
    {"question" : "Who was the 4th president of the United States?",
     "answer"   : "James Madison"},
    {"question" : "Who was the 5th president of the United States?",
     "answer"   : "James Monroe"},
    {"question" : "Who was the 6th president of the United States?",
     "answer"   : "John Quincy Adams"},
    {"question" : "Who was the 7th president of the United States?",
     "answer"   : "Andrew Jackson"},
    {"question" : "Who was the 8th president of the United States?",
     "answer"   : "Martin Van Buren"},
    {"question" : "Who was the 9th president of the United States?",
     "answer"   : "William Henry Harrison"},
    {"question" : "Who was the 10th president of the United States?",
     "answer"   : "John Tyler"},
    {"question" : "Who was the 11th president of the United States?",
     "answer"   : "James K. Polk"},
    {"question" : "Who was the 12th president of the United States?",
     "answer"   : "Zachary Taylor"},
    {"question" : "Who was the 13th president of the United States?",
     "answer"   : "Millard Fillmore"},
    {"question" : "Who was the 14th president of the United States?",
     "answer"   : "Franklin Pierce"},
    {"question" : "Who was the 15th president of the United States?",
     "answer"   : "James Buchanan"},
    {"question" : "Who was the 16th president of the United States?",
     "answer"   : "Abraham Lincoln"},
    {"question" : "Who was the 17th president of the United States?",
     "answer"   : "Andrew Johnson"},
    {"question" : "Who was the 18th president of the United States?",
     "answer"   : "Ulysses S. Grant"},
    {"question" : "Who was the 19th president of the United States?",
     "answer"   : "Rutherford B. Hayes"},
    {"question" : "Who was the 20th president of the United States?",
     "answer"   : "James A. Garfield"},
    {"question" : "Who was the 21st president of the United States?",
     "answer"   : "Chester A. Arthur"},
    {"question" : "Who was the 22nd president of the United States?",
     "answer"   : "Grover Cleveland"},
    {"question" : "Who was the 23rd president of the United States?",
     "answer"   : "Benjamin Harrison"},
    {"question" : "Who was the 24th president of the United States?",
     "answer"   : "Grover Cleveland"},
    {"question" : "Who was the 25th president of the United States?",
     "answer"   : "William McKinley"},
    {"question" : "Who was the 26th president of the United States?",
     "answer"   : "Theodore Roosevelt"},
    {"question" : "Who was the 27th president of the United States?",
     "answer"   : "William Howard Taft"},
    {"question" : "Who was the 28th president of the United States?",
     "answer"   : "Woodrow Wilson"},
    {"question" : "Who was the 29th president of the United States?",
     "answer"   : "Warren G. Harding"},
    {"question" : "Who was the 30th president of the United States?",
     "answer"   : "Calvin Coolidge"},
    {"question" : "Who was the 31st president of the United States?",
     "answer"   : "Herbert Hoover"},
    {"question" : "Who was the 32nd president of the United States?",
     "answer"   : "Franklin D. Roosevelt"},
    {"question" : "Who was the 33rd president of the United States?",
     "answer"   : "Harry S. Truman"},
    {"question" : "Who was the 34th president of the United States?",
     "answer"   : "Dwight D. Eisenhower"},
    {"question" : "Who was the 35th president of the United States?",
     "answer"   : "John F. Kennedy"},
    {"question" : "Who was the 36th president of the United States?",
     "answer"   : "Lyndon B. Johnson"},
    {"question" : "Who was the 37th president of the United States?",
     "answer"   : "Richard Nixon"},
    {"question" : "Who was the 38th president of the United States?",
     "answer"   : "Gerald Ford"},
    {"question" : "Who was the 39th president of the United States?",
     "answer"   : "Jimmy Carter"},
    {"question" : "Who was the 40th president of the United States?",
     "answer"   : "Ronald Reagan"},
    {"question" : "Who was the 41st president of the United States?",
     "answer"   : "George H. W. Bush"},
    {"question" : "Who was the 42nd president of the United States?",
     "answer"   : "Bill Clinton"},
    {"question" : "Who was the 43rd president of the United States?",
     "answer"   : "George W. Bush"},
    {"question" : "Who was the 44th president of the United States?",
     "answer"   : "Barack Obama"}

]

chemical_elements = [
    {"question" : "Most of the earth's atmosphere consists of this gas.",
     "answer"   : "N"},
    {"question" : "The symbol 'Au' refers to which chemical element?",
     "answer"   : "Gold"},
    {"question" : "The symbol 'Co' refers to which chemical element?",
     "answer"   : "Cobalt"},
    {"question" : "The symbol 'Cu' refers to which chemical element?",
     "answer"   : "Copper"},
    {"question" : "The symbol 'F' refers to which chemical element?",
     "answer"   : "Fluorine"},
    {"question" : "The symbol 'H' refers to which chemical element?",
     "answer"   : "Hydrogen"},
    {"question" : "The symbol 'Pb' refers to which chemical element",
     "answer"   : "Lead"},
    {"question" : "The symbol 'S' refers to which chemical element?",
     "answer"   : "Sulfur"},
    {"question" : "This element give plants the energy they need to grow.",
     "answer"   : "P"},
    {"question" : "This element is the building block of life.",
     "answer"   : "C"},
    {"question" : "This element was discovered by Hans Christian Oersted in 1825.",
     "answer"   : "Al"},
    {"question" : "This element was discovered by Joseph Priestly and Carl Scheele in 1774.",
     "answer"   : "O"},
    {"question" : "This element was discovered in 1808.",
     "answer"   : "B"},
    {"question" : "This element when combined with Chlorine makes table salt.",
     "answer"   : "Na"},
    {"question" : "What is the symbol for Potassium?",
     "answer"   : "K"},
    {"question" : "Which element has a reddish color in a gas and liquid state?",
     "answer"   : "Br"},
    {"question" : "Which element has a silver-gray appearance?",
     "answer"   : "Zn"},
    {"question" : "Which of these elements is considered a Metal.",
     "answer"   : "Fe"},
    {"question" : "Which of these elements is NOT considered a Metalloid.",
     "answer"   : "Sn"},
    {"question" : "Which of these elements is NOT considered a Noble Gas.",
     "answer"   : "H"}

]

Я видел несколько предыдущих ответов, они были связаны с ошибкой устаревшего элемента, которая решена. Я считаю, что это Вопрос №.

Ответы [ 2 ]

1 голос
/ 08 февраля 2020

Мне очень жаль. Я был сосредоточен на своем коде, а не на чем-то еще, я не заметил, что он всегда терпел неудачу в «пустяках химических элементов». Я также не смог заметить, что он всегда терпел неудачу в одном вопросе; Это потому, что я забыл вставить слово в словарь data.py. Сейчас все работает.

Спасибо всем за помощь. И еще раз прошу прощения

Я чувствую себя так глупо сейчас: /

0 голосов
/ 07 февраля 2020

Еще три идеи:

  1. Свободное ожидание:

    Wait<WebDriver> fluentWait = new FluentWait<>(driver) .withTimeout(30, TimeUnit.SECONDS) .pollingEvery(300, TimeUnit.MILLISECONDS) .ignoring(NoSuchElementException.class) .ignoring(StaleElementReferenceException.class);

    public WebElement fluentWait(By by) { WebElement waitElement = null; try { waitElement = fluentWait.until(webDriver -> getDriver().findElement(by)); } catch (TimeoutException ex) {} return waitElement; }

  2. Используйте класс действий

    WebElement element = fluentWait(by); Actions actions = new Actions(getDriver()); actions.moveToElement(element); actions.click(); actions.build().perform();

  3. Выясните, каких событий вы должны ждать. Приложение написано в Angular? Реагировать? JQuery?

https://www.swtestacademy.com/selenium-wait-javascript-angular-ajax/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...