没有这样的元素:无法在 Python/Selenium 中找到具有 ID 的元素

No such element: Unable to locate element with ID in Python/Selenium

在 Python 中使用 Selenium 在 USPS 职业网站上的搜索字段中输入文本时出现以下错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="WD40"]"}

网址是:https://wp1-ext.usps.gov/sap/bc/webdynpro/sap/hrrcf_a_unreg_job_search#

1
2
3
4
driver = webdriver.Chrome("C:/Users/NAME/Downloads/chromedriver_win32/chromedriver.exe")
driver.get("https://wp1-ext.usps.gov/sap/bc/webdynpro/sap/hrrcf_a_unreg_job_search#")
elem = driver.find_element_by_name("WD40")
elem.send_keys("denver")

当我深入选择器时,输入字段中有以下内容。

1
<input id="WD40" ct="I" lsdata="{29:'WD3E'}" lsevents="{Change:[{ResponseData:'delta',EnqueueCardinality:'single'},{}]}" type="text" tabindex="0" ti="0" class="lsField__input" autocomplete="off" autocorrect="off" name="WD40" style="width:350px;" title="">

所以我应该能够在 ID 字段中输入"WD40"的 ID,但我仍然收到该错误。

请发送帮助。


所需元素是动态元素,因此要使用 Selenium 在元素上定位/click(),您需要为 element_to_be_clickable() 诱导 WebDriverWait,并且可以使用以下任一定位器策略:

  • 使用 CSS_SELECTOR:

    1
    2
    driver.get("https://wp1-ext.usps.gov/sap/bc/webdynpro/sap/hrrcf_a_unreg_job_search#")
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"input.lsField__input"))).send_keys("denver")
  • 使用 XPATH:

    1
    2
    driver.get("https://wp1-ext.usps.gov/sap/bc/webdynpro/sap/hrrcf_a_unreg_job_search#")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,"//input[@class='lsField__input']"))).send_keys("denver")
  • 注意:您必须添加以下导入:

    1
    2
    3
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
  • 浏览器快照:

denver