簡體   English   中英

Selenium Python:從下拉列表中選擇元素

[英]Selenium Python : pick element from drop down in a span

我對 Selenium 比較陌生,我正在研究 web 瀏覽器自動化項目,其中一項操作是從下拉菜單中選擇一個元素,請在 html 代碼下方找到。

<span id="export_menu" class="ui-button drop-down export-menu" tabindex="0" role="application">
<span class="menu_text">Export</span>
<span class="drop-down-menu ui-icon ui-icon-triangle-1-s"></span>
<ul class="export-actions"><li><header>Export Report</header>
    <ul><li class="menu-action"><input type="button" value="CSV" class="button ui-button ui-widget ui-state-default ui-corner-all" id="export_csv" data-format="csv" role="button" aria-disabled="false"></li></ul>
    <ul><li class="menu-action"><input type="button" value="PDF" class="button ui-button ui-widget ui-state-default ui-corner-all" id="export_pdf" data-format="pdf" role="button" aria-disabled="false"></li></ul>
    <ul><li class="menu-action"><input type="button" value="Schedule Export" class="button ui-button ui-widget ui-state-default ui-corner-all" id="schedule" role="button" aria-disabled="false"></li></ul></li></ul>
</ul>
</span>

我在 Python 上嘗試了以下操作,它給出了如下錯誤

driver.find_element_by_id("export_menu").click()
driver.find_element_by_id("export_csv").click()

selenium.common.exceptions.ElementNotInteractableException:消息:元素無法滾動到視圖中

經過一些研究后,我也嘗試了以下操作,這只是超時

WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="export_csv"]'))).click()

請求幫助!

要從下拉菜單中選擇值為CSV的元素,您必須為element_to_be_clickable()引入WebDriverWait ,您可以使用以下任一解決方案:

  • 使用CSS_SELECTOR

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.ui-button.drop-down.export-menu#export_menu"))).click() WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "ul.export-actions li.menu-action > input.button.ui-button.ui-widget.ui-state-default.ui-corner-all#export_csv"))).click()
  • 使用XPATH

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@class='ui-button drop-down export-menu' and @id='export_menu']"))).click() WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='export-actions']//li[@class='menu-action']/input[@class='button ui-button ui-widget ui-state-default ui-corner-all' and @id='export_csv']"))).click()
  • 注意:您必須添加以下導入:

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

您可以在How to select an option from a dropdown of non select tag?

嘗試首先單擊<ul>

WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH, '//*[@class="export-actions"]'))).click()

WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="export_csv"]'))).click()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM