How to select an option from a dropdown of non select tag?

后端 未结 2 1910
有刺的猬
有刺的猬 2021-01-28 00:08

I am trying to select a value from a dropdown menu. I tried a lot of solutions found here but nothing work, sometimes I have the error can\'t scroll to view.

Code trials

相关标签:
2条回答
  • 2021-01-28 00:30

    The correct code would be

    s1=Select(driver.find_element_by_id('parentId'))
    s1.select_by_value('315')
    

    HTML attributes are very strict when it comes to extra spaces or line breaks, you need to provide value exactly as it is

    See Select Support chapter for Python WebDriver APIs designed for working with <select> tags

    With regards to overall test design a good idea is implementing Page Object Model Design Pattern, it will allow you to split UI and test logic and make your test robust, reliable and easier to refactor. See Page Objects chapter for more information.

    0 讨论(0)
  • 2021-01-28 00:45

    To select an option e.g. Automobiles from a dropdown menu of non <select> tag you can use the following solution:

    • Code Block:

      from selenium import webdriver
      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      
      options = webdriver.ChromeOptions()
      options.add_argument('start-maximized')
      driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
      driver.get('https://dzairannonces.com/posts/create')
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.select2-selection__rendered#select2-parentId-container"))).click()
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@class='select2-results']/ul//li[@class='select2-results__option' and contains(., 'Automobiles')]"))).click()
      
    • Browser Snapshot:

    0 讨论(0)
提交回复
热议问题