【发布时间】:2020-05-15 04:58:31
【问题描述】:
使用 python 和 selenium 在组合框下拉 ng select 中选择一个选项。我想在下拉选择中选择“男性”选项。我正在尝试使用 XPath。
我使用的代码:
driver.find_element_by_id("sex_0").click()
driver.find_element_by_xpath("//*[contains(text(), 'MALE')]").click()
复制并粘贴 HTML:
请选择选项女性
检查 HTML 的元素:
<ng-select _ngcontent-uau-c14="" bindlabel="cdDescr" bindvalue="cd" class="custom ng-select ng-select-single ng-select-searchable ng-untouched ng-pristine ng-valid ng-select-opened ng-select-bottom" placeholder="Please Select Option" role="listbox" title="Please Select Option" id="sex_0">
<div class="ng-select-container">
<div class="ng-value-container"><div class="ng-placeholder">Please Select Option</div><!----><!---->
<div class="ng-input" style="top: 0px;"><input role="combobox" type="text" autocomplete="ac08684b8af8" autocorrect="off" autocapitalize="off" aria-expanded="true" style="position: relative; top: 0px; left: -10px; padding-left: 10px; border: none !important; height: 45px; width: 468px;" aria-owns="ac08684b8af8" aria-activedescendant="ac08684b8af8-0"></div></div><!----><!---->
<span class="ng-arrow-wrapper"><span class="ng-arrow"></span></span></div><!---->
<ng-dropdown-panel class="ng-dropdown-panel ng-select-bottom" id="ac08684b8af8" style="opacity: 1;"><!---->
<div class="ng-dropdown-panel-items scroll-host"><div></div>
<div><!----><!---->
<div class="ng-option ng-option-marked" role="option" aria-selected="false" id="ac08684b8af8-0"><!----><!----><span class="ng-option-label">FEMALE</span></div>
<div class="ng-option" role="option" aria-selected="false" id="ac08684b8af8-1"><!----><!----><span class="ng-option-label">MALE</span></div>
<!----><!----><!----><!----></div></div><!----></ng-dropdown-panel></ng-select>
问题:
它将选择 FEMALE 而不是 MALE,因为 XPath 文本“FEMALE”包含文本“MALE”。我假设 'id="ac08684b8af8"' 是在每次使用时随机生成的,这意味着我不能使用 Selenium 按 id 查找元素。我尝试使用 selenium 进行选择,但出现错误:“ng 类型的元素选择未选择”。因此我使用了 XPath。当光标悬停在下拉选择上方时,“ng-option-marked”只是一个功能。
我应该如何解决这个问题?
【问题讨论】:
-
而不是包含使用这个
driver.find_element_by_xpath("//*[text()='MALE']").click()
标签: python html css selenium xpath