Я успешно написал сценарий Python для входа в веб-приложение на случай необходимости ожидания MFA. Он успешно переходит на страницу ввода данных, но затем не может идентифицировать ни одно из полей ввода данных; тайм-аут и выплевывание тех же ошибок. Я добавил немного «отладки» и даже создал файл source.html для устранения неполадок. Это сценарий, который я использую
Скрипт Python:
Код: Выделить всё
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
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.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import TimeoutException, NoSuchElementException, ElementNotInteractableException
# Initialize Chrome WebDriver using WebDriver Manager
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
# Navigate to the login page
driver.get('starting url')
# Locate the input fields and enter credentials
cruzid_field = driver.find_element(By.NAME, 'j_username')
password_field = driver.find_element(By.NAME, 'j_password')
# Enter your credentials
cruzid_field.send_keys('actual username')
password_field.send_keys('actual password')
# Click the login button
login_button = driver.find_element(By.NAME, '_eventId_proceed')
login_button.click()
# After successful login, locate the search input field and enter the search term
try:
WebDriverWait(driver, 60).until(EC.url_contains('next url'))
print("Logged in successfully!")
# Locate the search input field using its ID
search_field = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.ID, 'search-landing'))
)
search_field.send_keys('data entry code')
# Simulate pressing Enter to initiate the search
search_field.send_keys(Keys.RETURN)
# Switch to the iframe containing the content
print("Switching to iframe")
iframe = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.ID, 'bannerHS'))
)
driver.switch_to.frame(iframe)
print("Switched to iframe")
# Verify the current context is the iframe
current_frame = driver.execute_script("return self.name")
print(f"Current iframe context: {current_frame}")
# Wait for the tab-container element to be present after search (up to 120 seconds)
print("Waiting for the tab-container element to be present")
tab_container = WebDriverWait(driver, 120).until(
EC.presence_of_element_located((By.ID, 'tab-container'))
)
print("Tab-container element is present, search completed!")
# Attempt to locate the "Go" button using ID
print("Attempting to locate the Go button by ID")
go_button = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.ID, 'frames6'))
)
go_button.click()
print("Go button clicked successfully!")
# Wait for the pnlFgbjvch1Canvas element to appear
print("Waiting for pnlFgbjvch1Canvas element to be present")
pnl_element = WebDriverWait(driver, 60).until(
EC.presence_of_element_located((By.ID, 'pnlFgbjvch1Canvas'))
)
print("pnlFgbjvch1Canvas element is present")
# Adding a brief delay to ensure the element is ready for interaction
time.sleep(2)
***# Pause for manual date and document total entry*** PROBLEM 1
input("Please enter the transaction date and document total manually, then press Enter to continue...")
*# Wait for the specific div elements to be present* PROBLEM 2
print("Waiting for the view div element to be present")
view_div = WebDriverWait(driver, 60).until(
EC.presence_of_element_located((By.ID, 'view_16d82cc3-d839-4611-aaf5-6c06ddf7b162'))
)
print("View div element is present")
print("Waiting for the collapsible panel (rect145) to be present")
collapsible_panel = WebDriverWait(driver, 60).until(
EC.presence_of_element_located((By.ID, 'rect145'))
)
print("Collapsible panel (rect145) is present")
# Perform the tab action to move to the next field
print("Performing tab action")
body = driver.find_element(By.TAG_NAME, 'body')
body.send_keys(Keys.TAB)
print("Waiting for the frames29 panel to be present")
frames_panel = WebDriverWait(driver, 60).until(
EC.presence_of_element_located((By.ID, 'frames29'))
)
print("Frames29 panel is present")
# Click the input field with ID inp:fgbjvcdRuclCode
print("Locating the RUCL Code input field")
rucl_code_input = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.ID, 'inp:fgbjvcdRuclCode'))
)
rucl_code_input.click()
print("RUCL Code input field clicked")
# Read the 4-character code from the Excel file
print("Reading the 4-character code from the Excel file")
df = pd.read_excel('file/path')
code = df.iloc[0, 0]
print(f"Code read from Excel: {code}")
# Enter the code into the input field
print("Entering the code into the RUCL Code input field")
rucl_code_input.send_keys(code)
print("Complete")
time.sleep(30)
except (TimeoutException, NoSuchElementException, ElementNotInteractableException) as e:
print(f"Error occurred: {e}")
# Close the browser
driver.quit()
Я заменил задачу 1 следующей, чтобы использовать XPATH для идентификации поля. Когда я запустил его в первый раз, все прошло успешно и перешло к следующему полю. Во второй раз я запустил его; это не удалось. Время ожидания истекло, и не удалось идентифицировать и щелкнуть поле даты транзакции:
Код: Выделить всё
# Use a more robust XPath to locate the transaction date input field
print("Locating the transaction date input field")
transaction_date_input = WebDriverWait(driver, 20).until(
EC.presence_of_element_located(
(By.XPATH, '//input[contains(@id, "fgbjvchTransDate") and @name="fgbjvchTransDate"]'))
)
print("Transaction date input field located")
# Ensure the element is visible and interactable
WebDriverWait(driver, 20).until(
EC.visibility_of(transaction_date_input)
)
WebDriverWait(driver, 20).until(
EC.element_to_be_clickable(transaction_date_input)
)
# Click into the transaction date input field
print("Clicking the transaction date input field")
transaction_date_input.click()
# Perform the tab action
print("Performing tab action")
transaction_date_input.send_keys(Keys.TAB)


Подробнее здесь: https://stackoverflow.com/questions/786 ... ify-fields