简体   繁体   English

Selenium Python 中的 Select 下拉菜单

[英]Select dropdown in Selenium Python

I can't select values in a list.我不能 select 值在列表中。 I tried using find_element_by_class_name() to open the menu but when I need to select a <li> returns that element doesn't have a function click() .我尝试使用find_element_by_class_name()打开菜单,但是当我需要 select a <li>返回该元素没有 function click()

Here the code:这里的代码:

click_menu = driver.find_element_by_class_name("periodSelector")
click_menu[1].click()

Here is the HTML that I am trying to parse:这是我要解析的 HTML:

<div data-period-selector="" data-period="periodFilter">
    <div class="periodSelectorContainer">
        <div class="btn-group periodSelector">
            <button class="flat-btn dropdown-toggle periodToggle ng-binding" data-toggle="dropdown"> 20/02/2021 - 22/03/2021 <span class="dropdown-arrow"></span> </button>
            <ul class="dropdown-menu">
                <li>
                    <a href="javascript:void(0);" class="new-financ" ng-click="selectToday()"><i></i>
                        <span class="pull-left">Hoje</span>
                        <span class="pull-right"></span>
                    </a>
                </li>
                <li>
                    <a href="javascript:void(0);" class="new-financ" ng-click="selectThisWeek()"><i>
                </li>

There are multiple class names you have to use a css selector.有多个 class 名称,您必须使用 css 选择器。

click_menu = driver.find_element_by_css_selector("button.flat-btn.dropdown-toggle.periodToggle.ng-binding")
click_menu.click()

Clicks 1st li tag.点击第一个 li 标签。

driver.find_element_by_xpath("ul[@class='dropdown-menu']/li[1]").click()

periodSelector is a class on a DIV periodSelector是 DIV 上的 class

<div class="btn-group periodSelector">

I'm assuming that you need to click on the BUTTON我假设您需要单击 BUTTON

<button class="flat-btn dropdown-toggle periodToggle ng-binding" data-toggle="dropdown">

Most of those classes seem generic (probably not unique) but I'm guessing that periodToggle might be unique given the date range.这些类中的大多数看起来都是通用的(可能不是唯一的),但我猜想periodToggle在给定日期范围的情况下可能是唯一的。 Try尝试

driver.find_element_by_css_selector("button.periodToggle").click()

NOTE: You have an error in your code.注意:您的代码中有错误。 You are using .find_element_by_class_name() (singular) but have array notation on the next line, click_menu[1] .您正在使用.find_element_by_class_name() (单数),但在下一行click_menu[1]上有数组表示法。 In this case, you can just use click_menu.click() .在这种情况下,您可以只使用click_menu.click() You'd only need the array notation if you were using .find_elements_by_*() (note the plural, elements).如果您使用.find_elements_by_*() (注意复数,元素),则只需要数组表示法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM