繁体   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