首页 > 解决方案 > 如何使用 Selenium 和 Python 查找此示例的元素

问题描述

我需要在这个区域中找到一个元素,但是每次 id 和 name 都会改变,XPath 也是如此。也不能使用类,因为有两个字段具有相同的类:

driver.find_element_by_xpath('//*[@id="flightDepartureSearchAutoComplate3-0-69f"]').send_keys('AYT')

HTML:

<input name="flightDepartureSearchAutoComplate3-0-69f" id="flightDepartureSearchAutoComplate3-0-69f" type="text" ng-model="departureFlightSelectedDestination0" placeholder="From" class="form-control auto-complete ng-pristine ng-valid ng-valid-editable ng-empty ng-touched" uib-typeahead="departureFlightDestination as departureFlightDestination.label for departureFlightDestination in controller.getDepartureAutocomplete($viewValue,0) | limitTo: 10" typeahead-editable="false" typeahead-wait-ms="750" typeahead-min-length="3" typeahead-append-to="departureTargetElements[0]" typeahead-select-on-blur="true" typeahead-focus-on-select="false" typeahead-select-on-exact="true" typeahead-template-url="flightAutoComplateTypeaheadTemplate.html" typeahead-on-select="controller.departureAutoComplateChanged()" autocorrect="off" autocapitalize="off" autocomplete="off" spellcheck="false" b2b-validate="required" data-sln-id="slnTxt_departureFlightAutoComplate" autofocus="" aria-autocomplete="list" aria-expanded="false" aria-owns="typeahead-25-8460" style=""> 

错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="flightDepartureSearchAutoComplate3-0-22d"]"}
  (Session info: chrome=73.0.3683.103)
  (Driver info: chromedriver=73.0.3683.68 (47787ec04b6e38e22703e856e101e840b65afe72),platform=Windows NT 10.0.17134 x86_64)

标签: pythonseleniumxpathcss-selectorswebdriverwait

解决方案


所需的元素是Angular元素,因此要定位元素,您必须诱导WebDriverWait以使元素可点击,并且您可以使用以下任一定位器策略

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.form-control.auto-complete.ng-valid-editable[id^='flightDepartureSearchAutoComplate'][placeholder='From']"))).send_keys('AYT')
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='form-control auto-complete ng-pristine ng-valid ng-valid-editable ng-empty ng-touched' and starts-with(@id, 'flightDepartureSearchAutoComplate')][@placeholder='From']"))).send_keys('AYT')
    
  • 注意:您必须添加以下导入:

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

推荐阅读