python - 如何使用 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)
解决方案
所需的元素是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
推荐阅读
- java - Firestore 的 CompletableFuture
- python - 如何将循环在不同数据库上的 MySQL 查询组合到一个 excel 文件中(附加结果数据框)
- python - 从 Geopy 库中获取纬度和经度时出错
- android - findautocompletepredictionsrequest 是收费的吗?
- flowtype - 允许函数接受数组或元组,但强制数组文字在 Flow 中被视为元组
- java - 将 Java int 转换为 C 无符号 int
- django - 如何在没有 try 语句的情况下检测未处理的异常
- c# - Visual Studio Edit-GoToAll (CTRL+Comma) 包含引用程序集
- python-3.7 - 启动后的自定义调度程序线程由 gunicorn 的主线程和工作线程并行运行
- node.js - 参考错误:未定义文本编码器