如何使用Selenium和Python单击p-dropdown标记内的元素

时间:2018-08-01 17:47:15

标签: python selenium select selenium-webdriver webdriverwait

<p-dropdown _ngcontent-c16="" autofocus="" placeholder="Select Quota" class="ng-tns-c13-11 ui-inputwrapper-filled ng-untouched ng-pristine ng-valid">
  <div class="ng-tns-c13-11 ui-dropdown ui-widget ui-state-default ui-corner-all ui-helper-clearfix" style="width: 234px;">
    <div class="ui-helper-hidden-accessible ng-tns-c13-11 ng-star-inserted">
    <select class="ng-tns-c13-11" aria-hidden="true" tabindex="-1" aria-label="A">
      <option class="ng-tns-c13-11 ng-star-inserted">Select</option>
      <option class="ng-tns-c13-11 ng-star-inserted" value="GN">A</option>
      <option class="ng-tns-c13-11 ng-star-inserted" value="SS">B</option>
      <option class="ng-tns-c13-11 ng-star-inserted" value="LD">C</option>
      <option class="ng-tns-c13-11 ng-star-inserted" value="HP">D</option>
      <option class="ng-tns-c13-11 ng-star-inserted" value="TQ">E</option>
      <option class="ng-tns-c13-11 ng-star-inserted" value="PT">F</option>
      <!----></select>
    </div>

我需要在下拉列表中选择一个值 我尝试使用的xpath是:

driver.find_element_by_xpath("//*[@value='LD']").click()

但这表示未找到元素...可以使用什么其他表达式在DropDown中选择一个选项?

也可以像下面提到的那样做

driver.find_element_by_xpath(“ // * [@ placeholder ='Select Quota']”)。click()

还有其他事情吗?

3 个答案:

答案 0 :(得分:0)

此下拉列表是使用select和options标签构造的。所以选择类应该工作。

您可以尝试使用以下代码:

select = Select(driver.find_element_by_css_selector("select.ng-tns-c13-11"))

# select by visible text
select.select_by_visible_text('C')  

导入您将要做的:

from selenium.webdriver.support.ui import Select

答案 1 :(得分:0)

由于<select>元素是Angular元素,因此您必须诱使 WebDriverWait 使<select> 元素可点击并利用Select类,您可以使用以下解决方案:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
# other lines of code
mySelect = Select(WebDriverWait(driver, 20).until(EC.visibilty_of_element_located((By.XPATH, "//select[contains(@class,'ng-tns-') and @aria-label='A']"))))
# select by value
mySelect.select_by_value("LD")

答案 2 :(得分:0)

只需等待LD元素首先可点击,就像这样...

from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@value='LD']")))