Веб-автоматизация с использованием Python Script и Selenium в Microsoft Edge: ошибка при сохранении данныхPython

Программы на Python
Anonymous
Веб-автоматизация с использованием Python Script и Selenium в Microsoft Edge: ошибка при сохранении данных

Сообщение Anonymous »

Я пытался автоматизировать процесс ввода данных на веб-сайте.
  • Сервер работает слишком медленно
  • Процесс ввода данных сложен, поскольку на веб-сайте необходимо сделать десятки тысяч записей.
  • Элементы загружаются динамически.
  • Только выбран целевой раздел веб-страницы.
  • Время ожидания включено, чтобы обеспечить взаимодействие элементов.
Я пытался автоматизировать процесс с использованием Python и селена. Я использовал веб-драйвер для Microsoft Edge. Что-то не так с кодом, из-за которого он не может сохранить данные каждый раз.
Ниже приведен полный код, который я использовал.

Код: Выделить всё

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd
import time

# Load Excel data
excel_file = "***FILE PATH***"

# Load Habitation Code (Column B) and data from Columns H to P
df = pd.read_excel(excel_file, usecols="B,H:P", skiprows=0)
df.columns = ['Habitation Code'] + [f'Field_{i}' for i in range(1, 10)]

# Function to format decimal values
def format_decimal(value):
if pd.isna(value):
return ''
try:
# Check if the value contains a decimal point
if '.' in str(value):
# Convert to float for formatting
return f"{float(value):.3f}"
else:
# Return the value as is if it's a whole number
return str(value)
except ValueError:
return str(value)

# Apply formatting to relevant fields
for col in df.columns[1:]:
df[col] = df[col].apply(format_decimal)

# Configure Edge options to disable notifications and dialogs
edge_options = Options()
edge_options.add_argument("--disable-notifications")
edge_options.add_argument("--disable-popup-blocking")

# Path to Edge WebDriver executable
edge_driver_path = "C:\\WebDriver\\Edge\\msedgedriver.exe"

# Set up the Edge Service and WebDriver
service = Service(executable_path=edge_driver_path)
driver = webdriver.Edge(service=service, options=edge_options)

# Open the URL
driver.get('***URL***')

# Maximize the browser window
driver.maximize_window()

# Initialize WebDriverWait
wait = WebDriverWait(driver, 20)

# Wait for the page to load
time.sleep(20)

# Locate and interact with login elements
try:
wait.until(EC.visibility_of_element_located((By.XPATH, "//input[@id=':r2:']"))).send_keys('***USER ID***')
wait.until(EC.visibility_of_element_located((By.ID, 'eyePassword'))).send_keys('***PASSWORD***')
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Login']"))).click()
print("Login successful.")
except Exception as e:
print(f"Error during login: {e}")
driver.quit()

# Wait for the "Expand More" SVG element and click it
try:
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "svg[data-testid='ExpandMoreIcon']"))).click()
# Wait for the "Schema" SVG element and click it
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "svg[data-testid='SchemaIcon']"))).click()
# Wait for the "Edit" SVG element and click it
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "svg[data-testid='EditIcon']"))).click()
print("Navigated to Edit page.")
except Exception as e:
print(f"Error during navigation: {e}")
driver.quit()

# Locate and click the fifth "show more" button
try:
wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "button[aria-label='show more']")))[4].click()
time.sleep(15)
print("Clicked the fifth 'show more' button.")
except Exception as e:
print(f"Error finding 'show more' button: {e}")
driver.quit()

# Function to input data into table rows
def fill_table_data():
for i, row in df.iterrows():
habitation_code = row['Habitation Code']
data_columns = row[1:].tolist()  # Get data from columns H to P
updated = False  # Flag to track if any value was updated

try:
# Find the row element by habitation code
row_xpath = f"//tr[td[2][contains(text(), '{habitation_code}')]]"
row_element = wait.until(EC.presence_of_element_located((By.XPATH, row_xpath)))
print(f"Found row for Habitation Code {habitation_code}")

# Locate all input fields in the last 9  elements of the row
for j in range(7, 16):  # From the 8th to the 16th  (0-indexed)
try:
# Construct the XPath for the input field within the j-th   element
input_xpath = f"{row_xpath}/td[{j+1}]/div/div/input"
input_field = wait.until(EC.visibility_of_element_located((By.XPATH, input_xpath)))

# Scroll to the input field
driver.execute_script("arguments[0].scrollIntoView(true);", input_field)

# Format the new value
new_value = data_columns[j - 7]  # Get new value from data_columns

# Use JavaScript to directly set the value of the input field
driver.execute_script("arguments[0].value = arguments[1];", input_field, new_value)
# Trigger change event to ensure data is saved
driver.execute_script("arguments[0].dispatchEvent(new Event('change'));", input_field)

# Read back the value from the input field to verify
entered_value = input_field.get_attribute('value')
formatted_entered_value = format_decimal(entered_value)
print(f"Attempted to populate input in column {j+1} with data: {new_value}")
print(f"Actual value in input field for column {j+1}: {formatted_entered_value}")

# Compare and handle discrepancies
if formatted_entered_value != new_value:
print(f"Discrepancy detected in column {j+1} for Habitation Code {habitation_code}. Expected: {new_value}, Found: {formatted_entered_value}")
# Clear the field if values do not match
driver.execute_script("arguments[0].value = '';", input_field)
time.sleep(1)
continue

print(f"Successfully populated input in column {j+1} with data: {new_value}")
updated = True  # Set flag to true if a value was updated

# Wait 7 seconds before entering the next field
time.sleep(7)

except Exception as e:
print(f"Error locating or filling input field in column {j+1} for Habitation Code {habitation_code}: {e}")

if updated:
# Click the save button using the full XPath
try:
# Ensure the save button is in view
save_button_xpath = "//button[contains(@class, 'MuiButton-containedSAVE') and @type='submit']"
save_button = wait.until(EC.presence_of_element_located((By.XPATH, save_button_xpath)))
driver.execute_script("arguments[0].scrollIntoView(true);", save_button)

# Use JavaScript to click the button if standard click fails
driver.execute_script("arguments[0].click();", save_button)

print("Clicked the save button.")

# Wait for 90 seconds to ensure data is saved
time.sleep(90)
except Exception as e:
print(f"Error clicking save button: {e}")

print(f"Saved data for Habitation Code {habitation_code}")

except Exception as e:
print(f"Error processing row with Habitation Code {habitation_code}: {e}")

# Call the function to fill table data
fill_table_data()

# Keep the browser open until manually closed
print("Browser is open. Press Ctrl+C in the terminal to close it.")

# Keep the browser open indefinitely
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("Browser closed.")

# Close the browser
driver.quit()
Метод отправки ключей для заполнения полей ввода не сработал должным образом.
При нажатии кнопки сохранения вручную создается всплывающее окно «Сохранено успешно». сообщение на веб-странице, и оно исчезает почти мгновенно. Но я не знаю, как заставить сценарий дождаться этого сообщения и перейти к следующей записи.
На веб-странице есть несколько кнопок сохранения, и я попробовал использовать полный метод XPath и JavaScript, чтобы нажать кнопку «Сохранить», но, похоже, он не работает. Что здесь не так?
Веб-страница открывается почти мгновенно. Вход прошел успешно. Навигация по нужному разделу будет выполнена. Значения можно увидеть заполненными. Но сохранения данных не происходит. ТЕРМИНАЛ PYTHON ПОКАЗЫВАЕТ, ВСЕ ЗАВЕРШЕНО УСПЕШНО.
ПОМОГИТЕ МНЕ

Подробнее здесь: https://stackoverflow.com/questions/788 ... or-in-savi

Вернуться в «Python»