Как настроить таргетинг на DIV, который появляется только при наведении курсора на таблицуPython

Программы на Python
Ответить
Anonymous
 Как настроить таргетинг на DIV, который появляется только при наведении курсора на таблицу

Сообщение Anonymous »

Я пытаюсь выяснить, как парсить веб-сайт, и мне удалось получить желаемый результат, но я ограничен необходимостью удерживать курсор внутри таблицы, которую хочу прокрутить.
Конечная цель — запустить это в фоновом режиме без необходимости перемещать курсор или даже открывать страницу на переднем плане.
В ходе проверки я обнаружил, что этот div появляется, когда курсор находится внутри таблицы (который я хочу прокрутить) и исчезает, как только мышь выходит из него. Если я смогу изменить «верхнее» значение в этом div, я смогу добиться желаемого результата. HTML целевого DIV
Есть ли способ заставить DIV появляться без присутствия курсора? Или какой-нибудь другой обходной путь?
Как я уже упоминал, в настоящее время я полагаюсь на размещение курсора в таблице вручную, а затем отправку команды прокрутки. Я хочу полностью автоматизировать эту работу, чтобы она могла работать без открытия
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd
import time
from selenium.webdriver.common.action_chains import ActionChains
import pyautogui

# Set up the WebDriver
driver = webdriver.Chrome()

# Open the login page
driver.get('xxxxxxx')

# Wait for the username field and enter the username
username_field = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.XPATH, "//input[@placeholder='Crew ID']"))
)
username_field.send_keys('xxxxx') # Replace with your actual username

# Wait for the password field and enter the password
password_field = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.XPATH, "//input[@placeholder='Password']"))
)
password_field.send_keys('xxxxxx') # Replace with your actual password

# Submit the form
password_field.send_keys(Keys.RETURN)
time.sleep(3)

# Redirect to the required page
driver.get('xxxxxxxxxxxxxxxxxx')
time.sleep(5)

# Select "All Departures From"
try:
dropdown_icon = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, '.webix_input_icon.wxi-menu-down'))
)
dropdown_icon.click()
print("Dropdown icon clicked")

# Find and click the "All Departures From" option
all_departures_from_option = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//div[@role='gridcell' and @aria-rowindex='2' and text()='All Departures From']"))
)
all_departures_from_option.click()
print("All Departures From selected")
except Exception as e:
print(f"Error selecting 'All Departures From': {e}")

# Enter "BOM" into the Airport field
try:
# Find the input field by locating it under the "Airport" label
airport_label = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//label[text()='Airport']/following-sibling::div//input[@role='combobox']"))
)
airport_label.click()
airport_label.clear() # Clear any existing text in the field
time.sleep(3) # Pause to ensure the field clears
target_airport = "xxx"
airport_label.send_keys(target_airport)
print("'xxx' entered in the Airport field")
except Exception as e:
print(f"Error finding or entering 'xxx': {e}")
#---------------------------------------

# Use JavaScript to change the content of the specific parent div
new_date = "28/09/2024" # Replace with your desired date
script = """
var targetDiv = document.querySelector('div.webix_inp_static[aria-label="On"]');
if (targetDiv) {
targetDiv.innerText = arguments[0]; // Change the inner text
targetDiv.dispatchEvent(new Event('change')); // Trigger change event if necessary
} else {
return 'Target div not found';
}
"""
result = driver.execute_script(script, new_date)

# Check if there was an error message
if result:
print(result) # Print any error message returned by the script
else:
driver.find_element("css selector", 'body').send_keys(Keys.ENTER)
time.sleep(5)

#------------------Search for FO below--------------------

#------------------Search for FO below--------------------

def move_cursor_to_element(element):
"""Move the cursor to the given element using its absolute screen coordinates."""
# Get the element's location relative to the browser window
element_location = element.location
element_size = element.size

# Get the position of the browser window on the screen
browser_position = driver.execute_script("""
return {
x: window.screenX,
y: window.screenY
};
""")

# Calculate the absolute screen coordinates
x_position = element_location['x']
y_position = element_location['y']

# Move the cursor to the calculated screen position
pyautogui.moveTo(x_position, y_position)

def simulate_mouse_scroll():
"""Simulate mouse scroll using PyAutoGUI."""
pyautogui.scroll(-50) # Scroll down by 150 units
#print("scrolled by 150untis")

def check_fo_in_any_div(driver):
"""Search for 'FO' in any div and check its aria-rowindex."""

try:
# Wait for any div element containing the text "FO"
fo_divs = WebDriverWait(driver, 5).until(
EC.presence_of_all_elements_located((By.XPATH, '//div[contains(text(), "FO")]'))
)

# Loop through all divs containing "FO"
for fo_div in fo_divs:
# Get the aria-rowindex attribute
aria_rowindex = fo_div.get_attribute("aria-rowindex")
print(f"Found 'FO' in div with aria-rowindex: {aria_rowindex}")

# Check if the aria-rowindex is "2"
if aria_rowindex

Подробнее здесь: https://stackoverflow.com/questions/790 ... er-a-table
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

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