如何使用 selenium 填写表格?

How do I complete a form using selenium?

我想登录该网站,但无法添加我的凭据。

我的代码的第一部分是:

from selenium import webdriver

PATH = 'C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe'
driver = webdriver.Chrome(PATH)

driver.maximize_window()

driver.get('https://glovoapp.com/ro/buc/store/kaufland-buc/')

login = driver.find_element_by_xpath('//*[@id="user-login"]')

login.click()

之后,尝试使用 find_element_by_xpath() 和其他一些方法,但其中 none 有效,因为它显示“无法定位元素”或“元素不可交互”。我该怎么做?在之前的示例中,我可以使用 find_view_by_id() 找到它,但现在我遇到了一些问题。

要登录那个网站你需要诱导 WebDriverWait for the element_to_be_clickable() and you can use either of the following :

  • 使用CSS_SELECTOR:

    driver.get("https://glovoapp.com/ro/buc/store/kaufland-buc/")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#user-login"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div#login-email div input"))).send_keys("AlexBebereche@whosebug.com")
    
  • 使用XPATH:

    driver.get("https://glovoapp.com/ro/buc/store/kaufland-buc/")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@id='user-login']"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='login-email']//following::input[@data-test-id='text-field-input']"))).send_keys("AlexBebereche@whosebug.com")
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

浏览器快照: