无法在输入字段中输入文本(Python+Selenium)

2024-10-04 07:32:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在网页上有以下HTML代码片段:

<div class="f0n8F ">
    <label for="f395fbf9cde026" class="_9nyy2">Phone number, username, or email</label>
    <input class="_2hvTZ pexuQ zyHYP" id="f395fbf9cde026" aria-describedby="slfErrorAlert" aria-label="Phone number, username, or email" aria-required="true" autocapitalize="off" autocorrect="off" maxlength="75" name="username" type="text" value="">
</div>

我尝试使用以下代码输入文本:

username_element = WebDriverWait(driver, 5).until(expected_conditions.visibility_of_element_located((By.ID, "f395fbf9cde026")))
username_element.send_keys('abc')

即使我尝试(By.CLASS, "class _2hvTZ pexuQ zyHYP")(By.XPATH, "//*[@id=\"f1798b97d45a38\"]"),我也会不断得到一个超时异常。你知道吗

如果我尝试By.NAME, "username",在前一页上有另一个名为'username'的元素,因此在执行上述代码行之前,在前一页上输入'abc'。你知道吗

值得注意的是,如果我尝试driver.implicitly_wait(x),就不会发生等待。你知道吗


Tags: or代码divnumberbyemailusernamephone
2条回答

尝试使用xpath,它应该是唯一的。你知道吗

username_element = WebDriverWait(driver, 5).until(expected_conditions.element_to_be_clickable((By.XPATH, "//input[@name='username'][@aria-describedby='slfErrorAlert']")))
username_element.send_keys('abc')

所需的元素是动态元素,因此要发送字符序列,必须为element_to_be_clickable()诱导WebDriverWait,并且可以使用以下Locator Strategies

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[aria-describedby='slfErrorAlert'][name='username']"))).send_keys("KOB")
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@aria-describedby='slfErrorAlert' and @name='username']"))).send_keys("KOB")
    
  • 注意:必须添加以下导入:

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

相关问题 更多 >