使用python从下拉菜单中选择项目

时间:2019-04-27 14:37:16

标签: python selenium selenium-webdriver pycharm

我正在使用Selenium来获取网页中的一些信息,但是我需要首先在下拉菜单列表中选择一个特定项目。页面的外观如下:

enter image description here

我想单击“跟踪器可用性”选项。我尝试获取该类(在图像中突出显示)并更改它的值,但这不起作用...任何帮助将不胜感激!

编辑HTML代码:

<select class="ng-valid ng-touched ng-not-empty ng-dirty ng-valid-parse"> style="width: 100px; height: 33px; margin-left: 5px; border-radius: 2px;" ng-model="$ctrl.selectedScratchPad" ng-options="s.name for s in $ctrl.scratchPads track by s.name" ng-change="$ctrl.scratchPadSelected($ctrl.selectedScratchPad)"
<!-- ngIf: $ctrl.selectedScratchPad === null -->
<option label="G&T" value="G&T" selected="selected">G&T</option>
<option label="Relatório semanal" value="Relatório semanal" selected="selected">Relatório semanal</option>
<option label="CBs current" value="CBs current">CBs current</option>
<option label="Tracker Availability" value="Tracker Availability">Tracker Availability</option>
<option label="INV 5-1 Trackers target" value="INV 5-1 Trackers target">INV 5-1 Trackers target</option>
<option label="INV 5-1 Trackers current" value="INV 5-1 Trackers current">INV 5-1 Trackers current</option>
<option label="INV 5-1 Trackers availability" value="INV 5-1 Trackers availability">INV 5-1 Trackers availability</option>
<option label="PVSyst Input" value="PVSyst Input">PVSyst Input</option>

2 个答案:

答案 0 :(得分:1)

这里是直接单击列表项的选项。

driver.find_element_by_xpath("//select[@ng-model='$ctrl.selectedScratchPad']/option[.='Tracker Availability']").click()

答案 1 :(得分:1)

您可以使用<select>类从Select元素中选择选项,而不是单击选择。

尝试一下:

element = WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.XPATH,"//select[@ng-model='$ctrl.selectedScratchPad']")))
dropdown = Select(element)
dropDown.select_by_visible_text("Tracker Availability")

为此,您必须导入以下内容。

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