【问题标题】:Problem Selecting Okay Button with Python and Selenium使用 Python 和 Selenium 选择确定按钮的问题
【发布时间】:2020-07-13 20:38:55
【问题描述】:

所以我遇到了一个问题,我无法从新窗口中弹出的警报消息中选择okay。我真的不知道该怎么做,真的只是想接受警报,因为所有工作都已完成以确保处理删除。整个脚本的代码可以在这里找到:https://github.com/Richard-Barrett/ITDataServicesInfra/blob/master/Python/Skyward/Administration/remove_sec_groups_inactive_users.py

代码:

#!/bin/usr/env python
# ===========================================================
# Created By: Richard Barrett
# Organization: DVISD
# DepartmenT: Data Services
# Purpose: Skyward Administration
# Date: 04/01/2020
# ===========================================================

import selenium
import shutil
import xlsxwriter
import os
import unittest
import requests
import subprocess
import getpass
import platform
import pynput
import logging
import time 
from pynput.keyboard import Key, Controller
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait 
from datetime import date

decrypt = "gpg --output secrets.json --decrypt secrets.gpg" 

if os.path.exists("secrets.gpg"):
      returned_value = subprocess.call(decrypt, shell=True)
else:
        print("The file does not exist!")
        print("You should probably create a secret!")
        print("gpg --output filename.gpg --encrypt filename.json")

import json
with open('secrets.json','r') as f:
      config = json.load(f)

# Definitions
# find_elements_by_name
# find_elements_by_xpath
# find_elements_by_link_text
# find_elements_by_partial_link_text
# find_elements_by_tag_name
# find_elements_by_class_name
# find_elements_by_css_selector

# System Variables
today = date.today()
date = today.strftime("%m/%d/%Y")
node = platform.node()
system = platform.system()
username = getpass.getuser()
version = platform.version()
keyboard = Controller()

# Upload Path Variables 
file_input_inactive_users = os.path.abspath("C:\Imports\CustomNameNeedsFormatting_02_24_2020_20_14_12_richardbarrett")

# URL Variables 
login_url = ''
redirect_url = ''
reports_scheduler_url = ''
custom_reports_url = ''

# Check for Version of Chrome

# WebDriver Path for System
if platform.system() == ('Windows'):
    browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\chromedriver.exe")
elif platform.system() == ('Linux'):
    browser = webdriver.Chrome(executable_path='/home/rbarrett/Drivers/Google/Chrome/chromedriver_linux64/chromedriver')
elif platform.system() == ('Darwin'):
    browser = webdriver.Chrome(executable_path='~/Drivers/Google/Chrome/chromedriver_mac64/chromedriver')
else:
    print("Are you sure you have the Selenium Webdriver installed in the correct path?")

# tearDown Method
def tearDown(self):
    self.browser.close()

# shutDown Method 
def shutDown(self):
    self.browser.quit()

# Parent URL
browser.get("https://skyward-student.del-valle.k12.tx.us/scripts/wsisa.dll/WService=wsEAplus/seplog01.w?nopopup=true")
time.sleep(5)

# Credentials NEEDS UNIT TEST
username = browser.find_element_by_id("login")
password = browser.find_element_by_id("password")
username.send_keys(config['user']['name'])
password.send_keys(config['user']['password'])

# Authentication submit.click()
# For XPATH = //*[@id='bLogin']
element = WebDriverWait(browser, 20).until(
    EC.element_to_be_clickable((By.XPATH, "//*[@id='bLogin']")))
element.click();
print("Logging into <insert_program>!")
print("Authenticated")

# Click and Span Skyward Contact Access
# Adminsitration XPATH = //*[@id='nav_ContactAccess']/span
element = WebDriverWait(browser, 20).until(
            EC.element_to_be_clickable((By.XPATH, "//*[@id='nav_ContactAccess']/span")))
element.click();

# Click on Secured Users
# XPATH = //a[@id='nav_SecuredUsers']/span
element = WebDriverWait(browser, 20).until(
            EC.element_to_be_clickable((By.XPATH, "//a[@id='nav_SecuredUsers']/span")))
element.click();

# Load users.json File 
with open('users.json','r') as f:
          config = json.load(f)

# Send Keys to Lookup 
# XPATH = //*[@id='brSecuredUsersLookupInput']
target_user = WebDriverWait(browser, 20).until(
                    EC.element_to_be_clickable((By.XPATH, "//*[@id='brSecuredUsersLookupInput']")))
target_user.send_keys(config['sec_group_removal']['name_key']);
target_user.send_keys(Keys.RETURN);

# Expand Button on Element Needing Sec Group Removal
# Class "bd_open"
element = WebDriverWait(browser, 20).until(
            EC.element_to_be_clickable((By.CLASS_NAME, "bd_closed")))
element.click()

# Click on Remove All Groups By Link Text
# find_elements_by_link_text
element = WebDriverWait(browser, 20).until(
                    EC.element_to_be_clickable((By.LINK_TEXT, "Remove All Groups")))
element.click()

# Browser Switches to New Window Alert for Verification
# Browser Switches to Window
WebDriverWait(browser,10).until(EC.number_of_windows_to_be(2))
browser.switch_to.window(browser.window_handles[-1])

# Click Ok by ID
# XPATH //*[@id='msgBtn1'] 
element = WebDriverWait(browser, 20).until(
                            EC.element_to_be_clickable((By.XPATH, "//*[@id='msgBtn1']")))
element.click()

点击删除所有组后,会弹出一条消息,如下所示:

我认为部分代码是我没有正确处理它,因为它没有切换到窗口:

# Browser Switches to New Window Alert for Verification
# Browser Switches to Window
WebDriverWait(browser,10).until(EC.number_of_windows_to_be(2))
browser.switch_to.window(browser.window_handles[-1])

这是我需要点击的元素的副本:

<a class="button" id="msgBtn1" tabindex="5" href="javascript:if (cbs('msgBtn1')) {closeMessage(false); validateForm('xAllGroups','ssusrhttp001.w','ssusrbrws001.w'); cancelEvent();}" role="button" style="width: 100px; font-weight: normal;">OK&nbsp;</a>

【问题讨论】:

    标签: python python-3.x selenium-webdriver selenium-chromedriver browser-automation


    【解决方案1】:

    原来我不需要切换到窗口。警报是主页的一部分。我拿出了

    # Browser Switches to New Window Alert for Verification
    # Browser Switches to Window
    WebDriverWait(browser,10).until(EC.number_of_windows_to_be(2))
    browser.switch_to.window(browser.window_handles[-1])
    

    现在代码看起来像这样,它工作得很好:

    #!/bin/usr/env python
    # ===========================================================
    # Created By: Richard Barrett
    # Organization: DVISD
    # DepartmenT: Data Services
    # Purpose: Skyward Administration
    # Date: 04/01/2020
    # ===========================================================
    
    import selenium
    import shutil
    import xlsxwriter
    import os
    import unittest
    import requests
    import subprocess
    import getpass
    import platform
    import pynput
    import logging
    import time 
    from pynput.keyboard import Key, Controller
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.ui import WebDriverWait 
    from datetime import date
    
    decrypt = "gpg --output secrets.json --decrypt secrets.gpg" 
    
    if os.path.exists("secrets.gpg"):
          returned_value = subprocess.call(decrypt, shell=True)
    else:
            print("The file does not exist!")
            print("You should probably create a secret!")
            print("gpg --output filename.gpg --encrypt filename.json")
    
    import json
    with open('secrets.json','r') as f:
          config = json.load(f)
    
    # Definitions
    # find_elements_by_name
    # find_elements_by_xpath
    # find_elements_by_link_text
    # find_elements_by_partial_link_text
    # find_elements_by_tag_name
    # find_elements_by_class_name
    # find_elements_by_css_selector
    
    # System Variables
    today = date.today()
    date = today.strftime("%m/%d/%Y")
    node = platform.node()
    system = platform.system()
    username = getpass.getuser()
    version = platform.version()
    keyboard = Controller()
    
    # Upload Path Variables 
    file_input_inactive_users = os.path.abspath("C:\Imports\CustomNameNeedsFormatting_02_24_2020_20_14_12_richardbarrett")
    
    # URL Variables 
    login_url = ''
    redirect_url = ''
    reports_scheduler_url = ''
    custom_reports_url = ''
    
    # Check for Version of Chrome
    
    # WebDriver Path for System
    if platform.system() == ('Windows'):
        browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\chromedriver.exe")
    elif platform.system() == ('Linux'):
        browser = webdriver.Chrome(executable_path='/home/rbarrett/Drivers/Google/Chrome/chromedriver_linux64/chromedriver')
    elif platform.system() == ('Darwin'):
        browser = webdriver.Chrome(executable_path='~/Drivers/Google/Chrome/chromedriver_mac64/chromedriver')
    else:
        print("Are you sure you have the Selenium Webdriver installed in the correct path?")
    
    # tearDown Method
    def tearDown(self):
        self.browser.close()
    
    # shutDown Method 
    def shutDown(self):
        self.browser.quit()
    
    # Parent URL
    browser.get("https://skyward-student.del-valle.k12.tx.us/scripts/wsisa.dll/WService=wsEAplus/seplog01.w?nopopup=true")
    time.sleep(5)
    
    # Credentials NEEDS UNIT TEST
    username = browser.find_element_by_id("login")
    password = browser.find_element_by_id("password")
    username.send_keys(config['user']['name'])
    password.send_keys(config['user']['password'])
    
    # Authentication submit.click()
    # For XPATH = //*[@id='bLogin']
    element = WebDriverWait(browser, 20).until(
        EC.element_to_be_clickable((By.XPATH, "//*[@id='bLogin']")))
    element.click();
    print("Logging into <insert_program>!")
    print("Authenticated")
    
    # Click and Span Skyward Contact Access
    # Adminsitration XPATH = //*[@id='nav_ContactAccess']/span
    element = WebDriverWait(browser, 20).until(
                EC.element_to_be_clickable((By.XPATH, "//*[@id='nav_ContactAccess']/span")))
    element.click();
    
    # Click on Secured Users
    # XPATH = //a[@id='nav_SecuredUsers']/span
    element = WebDriverWait(browser, 20).until(
                EC.element_to_be_clickable((By.XPATH, "//a[@id='nav_SecuredUsers']/span")))
    element.click();
    
    # Load users.json File 
    with open('users.json','r') as f:
              config = json.load(f)
    
    # Send Keys to Lookup 
    # XPATH = //*[@id='brSecuredUsersLookupInput']
    target_user = WebDriverWait(browser, 20).until(
                        EC.element_to_be_clickable((By.XPATH, "//*[@id='brSecuredUsersLookupInput']")))
    target_user.send_keys(config['sec_group_removal']['name_key']);
    target_user.send_keys(Keys.RETURN);
    
    # Expand Button on Element Needing Sec Group Removal
    # Class "bd_open"
    element = WebDriverWait(browser, 20).until(
                EC.element_to_be_clickable((By.CLASS_NAME, "bd_closed")))
    element.click()
    
    # Click on Remove All Groups By Link Text
    # find_elements_by_link_text
    element = WebDriverWait(browser, 20).until(
                        EC.element_to_be_clickable((By.LINK_TEXT, "Remove All Groups")))
    element.click()
    
    # Click Ok by ID
    # XPATH //*[@id='msgBtn1'] 
    element = WebDriverWait(browser, 20).until(
                                EC.element_to_be_clickable((By.XPATH, "//*[@id='msgBtn1']")))
    element.click()
    

    【讨论】:

      【解决方案2】:

      找出这些问题的最简单方法是使用Selenium IDE browser plugin。在那里,您可以手动完成应用程序的步骤、保存、运行以确保其正常工作。这一切都是通过简单地与您的网络应用程序交互(如录制宏)来实现的。它的美妙之处在于,它为您生成代码并识别定位对象以进行交互(或定位信息以进行自动化测试)所必需的 CSS/HTML 选择器

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-27
        • 2018-08-04
        • 2015-07-22
        • 2016-08-10
        • 2014-03-21
        • 1970-01-01
        • 1970-01-01
        • 2019-10-29
        相关资源
        最近更新 更多