我无法在模态框内的输入中写入内容。单击按钮后会打开此模式。
以下是链接:
https://www.portalinmobiliario.com/MLC-2148268902-departamento-los-espinos-id-116373-_JM#position=1&search_layout=grid&type=item&tracking_id=eba8327b-85c0-4317-8c63-7c69c5b34e16
首先,使用此功能,单击按钮:
def button_click(self, xpath):
time.sleep(2)
button = self.driver.find_element(
By.XPATH, xpath)
button.click()
time.sleep(5)
按钮的xpath如下:
"/html/body/div[2]/div/button"
模式打开后,我尝试操作模式的输入并在其中写入。 我使用以下功能:
def write_input(self, xpath, answer):
time.sleep(2)
winput = self.driver.find_element(
By.XPATH, xpath)
winput.send_keys(answer)
time.sleep(5)
尝试使用这个 xpath:
/html/body/div[4]/div/div/div[2]/div[2]/div/div[2]/form/div[1]/div[1]/div/input
出现以下错误:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[4]/div/div/div[2]/div[2]/div/div[2]/form/div[1]/div[1]/div/input"}
流程是打开链接 --> 单击按钮“Contactar” --> 模式打开并输入内容
如何找到模态框内的元素?
您的按钮具有分配给它的防抖逻辑。 这意味着只有在去抖动结束后,单击操作才会成功。这可能需要 1 秒以上(取决于站点实施)。
所以渲染后点击按钮不会触发模态。您需要通过脏
time.sleep(2)
或更多等待一段时间或实现重试逻辑click_with_retry
。
并尽量避免绝对xPath。您的资源具有独特且可读的属性,可用于构建独特的定位器。
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def click_and_wait_for_modal_with_retry(driver, max_retries, button_locator, by, dialog_locator):
retries = 0
while retries < max_retries:
button = WebDriverWait(driver, 10).until(EC.presence_of_element_located(button_locator))
button.click()
time.sleep(0.5)
if len(driver.find_elements(by, dialog_locator)) > 0 and driver.find_elements(by, dialog_locator)[0].is_displayed():
break
retries += 1
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 20)
driver.maximize_window()
driver.get(
'https://www.portalinmobiliario.com/MLC-2148268902-departamento-los-espinos-id-116373-_JM#position=1&search_layout=grid&type=item&tracking_id=eba8327b-85c0-4317-8c63-7c69c5b34e16')
consent = wait.until(EC.presence_of_element_located((By.ID, 'newCookieDisclaimerButton')))
consent.click()
wait.until(EC.staleness_of(consent))
click_and_wait_for_modal_with_retry(driver, 3, (By.CSS_SELECTOR, 'button[type=primary] .andes-button__content'),
By.CSS_SELECTOR, '.andes-modal__overlay')
dialog = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '.andes-modal__overlay')))
wait = WebDriverWait(dialog, 10)
name = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '[data-testid=name-input]')))
name.send_keys('name')