Search code examples
javascriptpythonseleniumsetvalue

Python Selenium: Possible to change value when clicking option in dropdown menu?


I am using python selenium to conduct some searches. On one web page I query, the search dialogue allows me to specify via dropdown menu if I want to search all sections, or a specific, section. To select which section, the site has some separate dialogue in a popup where I can click on one section, and thereafter, the option "this section" in the dropdown menu is internally assigned the value of the selected section. This is how the selector looks if inspected:

    <select ...>
      <option id="searchthissection" value="<sectionname>">Search only in this section</option>
      <option id="searchallsections" value="">Search in all sections</option>
    </select>

The value is thus set by the external popup dialogue. Once set, I trigger the option as follows:

    webdriver.find_element_by_xpath("//select[@id='searchoption']/option[text()'Search only in this section']").click()

Now, I can in principle use selenium to open the selection popup, switch to it, find the section, click, switch back, and select the option "searchthissection". But that is incredibly inefficient, also because the popup loads slowly and has multiple pages of options to switch through.

I can easily list/generate all the values I would like to take. Is there a way to set the value directly while clicking the option? I am thinking of something like this:

    webdriver.find_element_by_xpath("//select[@id='searchoption']/option[text()'Search only in this section']").set_value('<sectionname>').click()

Any ideas? Thanks a lot!


Solution

  • ok I solved it. what i did is this. option=webdriver.find_element_by_xpath(...), webdriver.execute_script("arguments[0].value='<sectionname>';",option), and then trigger the search by sending keys to the text field, sending key ENTER (for some reason, option.click() does not work)