Selenium - Python - Select dropdown meun option -

2019-09-08 17:30发布

I am trying to select and element in a dropdown menu:

The HTML is:

<div class="col-lg-6">
       <select data-bind="options: indicator_type_list,value: indicatorType,optionsCaption: 'Choose...', disable: $root.mode().isReadOnly()">
        <option value="">Choose...</option>
        <option value="Malicious E-mail">Malicious E-mail</option>
        <option value="IP Watchlist">IP Watchlist</option>
        <option value="File Hash Watchlist">File Hash Watchlist</option>
        <option value="Domain Watchlist">Domain Watchlist</option>
        <option value="URL Watchlist">URL Watchlist</option>
        <option value="Malware Artifacts">Malware Artifacts</option>
        <option value="C2">C2</option>
        <option value="Anonymization">Anonymization</option>
        <option value="Exfiltration">Exfiltration</option>
        <option value="Host Characteristics">Host Characteristics</option>
        <option value="Compromised PKI Certificate">Compromised PKI Certificate</option>
        <option value="Login Name">Login Name</option>
        <option value="IMEI Watchlist">IMEI Watchlist</option>
        <option value="IMSI Watchlist">IMSI Watchlist</option>
       </select>
</div>

I have tried:

Select = Select(browser.find_element_by_xpath("//div[contains(.,'Choose...Malicious E-mailIP WatchlistFile Hash WatchlistDomain WatchlistURL WatchlistMalware ArtifactsC2AnonymizationExfiltrationHost CharacteristicsCompromised PKI CertificateLogin NameIMEI WatchlistIMSI Watchlist')]"))

and

test = browser.find_element_by_xpath("//option[@value='Malicious E-mail']") 
dropdown = test.find_element_by_xpath('..')
select = Select(browser.dropdown)

However I cannot seem to find the element to select the items in the dropdown.

Any help is appreciated!

2条回答
贼婆χ
2楼-- · 2019-09-08 17:42

You can use Select by giving it web element with select tag

select = Select(browser.find_element_by_css_selector(".col-lg-6 > select")) #finds the select tag
select.select_by_value("Malicious E-mail")
#or
select.select_by_visible_text("Malicious E-mail")
查看更多
爷、活的狠高调
3楼-- · 2019-09-08 17:49

There are multiple ways to locate this select element.

Here is one way - locate the select element that has a specific option inside:

from selenium.webdriver.support.select import Select

option_value = "Malicious E-mail"

select_element = browser.find_element_by_xpath("//select[option[@value = '%s']]" % option_value)
select = Select(select_element)
select.select_by_value(option_value)
查看更多
登录 后发表回答