我需要在此区域中找到一个元素,但是每次更改ID和名称时,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)
答案 0 :(得分:1)
所需元素是一个Angular元素,因此要定位该元素,必须诱使 WebDriverWait 使元素可点击,并且您可以使用以下任意一种以下Locator Strategies:
使用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