【问题标题】:How do I identify the element by the class with Selenium and Python?如何使用 Selenium 和 Python 按类识别元素?
【发布时间】:2021-01-18 21:20:33
【问题描述】:
<input class="inputDefault-_djjkz input-cIJ7To" name="password" type="password" placeholder="" aria-label="Password" autocomplete="off" maxlength="999" spellcheck="false" value="">```

^这是 HTML 我一直在尝试类似的东西

login = driver.find_element_by_xpath(".//*[@class='inputDefault-_djjkz input-cIJ7To']/div/input").click()

感谢您的帮助

【问题讨论】:

    标签: python selenium-webdriver xpath css-selectors webdriverwait


    【解决方案1】:

    您可以使用以下代码:

    driver.find_element_by_xpath("//input[@class='inputDefault-_djjkz input-cIJ7To']")
    

    【讨论】:

    • _djjkzcIJ7To 是动态值,会在每个新会话中更改。
    • 好的,在这种情况下,您可以使用名称“password”获取它 driver.find_element_by_xpath("//input[@name='password']")
    【解决方案2】:

    要识别可点击元素,您可以使用以下任一Locator Strategies

    • 使用css_selector

      element = driver.find_element(By.CSS_SELECTOR, "input[name='password'][aria-label='Password']")
      
    • 使用xpath

      element = driver.find_element(By.XPATH, "//input[@name='password' and @aria-label='Password']")
      

    理想情况下,要识别您需要为element_to_be_clickable() 诱导WebDriverWait 的元素,您可以使用以下任一Locator Strategies

    • 使用CSS_SELECTOR:

      element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='password'][aria-label='Password']")))
      
    • 使用XPATH

      element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='password' and @aria-label='Password']")))
      
    • 注意:您必须添加以下导入:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2020-09-20
      • 1970-01-01
      • 2019-09-21
      • 2019-09-22
      相关资源
      最近更新 更多