justin_sakong
justin_sakong

Reputation: 289

How to select a value from options as per the HTML through Selenium and Python

I'm trying to change the value of a dropdown and facing problem while selecting the value from <select> tag and <option> tag.

This is HTML that i want to change.

<form name="frmSearch" action="" onsubmit="return false;">
  <span class="seljs_title                            ">
    <input id="searchByInput91" name="searchBy91" type="text" readonly="readOnly" class="m-tcol-c" style="width: 110px;">
    <input type="hidden" name="searchBy" value="0" style="display: none;">
  </span>
  <select id="searchBy" name="" class="m-tcol-c" onchange="$('query').focus();" style="width:110px;display:none;">
    <option value="0">one</option>
    <option value="1">two</option>
    <option value="3">three</option>
    <option value="4">four</option>
    <option value="5">five</option>
  </select>
  <input type="text" id="query" name="query" style="ime-mode:active" value="" onkeydown="if (event.keyCode == 13) {nhn.search.goSearch(event);clickcr(this, 'sch.bsearch','','',event)}"
    class="m-tcol-c border-sub text">
  <a href="#" onclick="nhn.search.goSearch(event);clickcr(this, 'sch.bsearch','','',event); return false;">
    <img src="https://cafe.pstatic.net/cafe4/hidden.gif" width="42" height="21" alt="검색" class="btn-search-green">
  </a>
</form> 

I'm using Webdriver(Chrome).This is my code.

driver.find_element_by_name('frmSearch').find_element_by_id('searchByInput91').click()

This code makes me to click the dropdown and open the options. After that, when I use this code :

from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_id('searchBy'))
select.select_by_value('1').click()

OR

driver.find_element_by_id("searchBy").send_keys("two")

Error messages always come out.

ElementNotVisibleException: Message: element not visible: Element is not currently visible and may not be manipulated   
  (Session info: chrome=69.0.3497.81)   
  (Driver info: chromedriver=2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e),platform=Windows NT 10.0.17134 x86_64)

what should I do?

Upvotes: 0

Views: 1030

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193108

As per the HTML you have provided it seems that the <select> tag contains style attribute as display: none;. So you can use the following solution to select an option:

from selenium.webdriver.support.ui import Select
# other lines of code
driver.find_element_by_name('frmSearch').find_element_by_id('searchByInput91').click()
element = driver.find_element_by_xpath("//select[@class='m-tcol-c' and @id='searchBy']")
driver.execute_script("arguments[0].removeAttribute('style')", element)
select = Select(driver.find_element_by_xpath("//select[@class='m-tcol-c' and @id='searchBy']"))
select.select_by_value('1')

Upvotes: 1

Related Questions