-1

I'm trying to access the select element on this page: https://yt5s.com/en133?q=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSBjQ9tuuTJQ

I'm using the following code to access the dropdown:

  driver.findElement(By.xpath("//select[@class='form-control form-control-small hidden']/optgroup[@label='mp3']")).click();

But I receive the following error

Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//select[@class='form-control form-control-small hidden']/optgroup[@label='mp3']"}

The following answers in this chain are all correct. I found the issue to be that my code opened the above url in a new tab and I didn't switch to this new tab yet. The following piece of code let me switch to the new tab and now it is working.

ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.close();
driver.switchTo().window(tabs.get(1));
Prophet
  • 32,350
  • 22
  • 54
  • 79
Prem P.
  • 415
  • 2
  • 4
  • 19

2 Answers2

1

Because of optgroups inside the Select we can't use here regular Selenium Select mechanism. Your locator is wrong.
Please try this:

driver.findElement(By.xpath("//select[@id='formatSelect']//optgroup[@label='mp3']//option[@data-format='mp3']")).click();

In case the command above will not work directly try first to open the dropdown by

driver.findElement(By.xpath("//select[@id='formatSelect']")).click();

And then to select the desired option with

driver.findElement(By.xpath("//select[@id='formatSelect']//optgroup[@label='mp3']//option[@data-format='mp3']")).click();
Prophet
  • 32,350
  • 22
  • 54
  • 79
  • Apologies for not giving enough issue, I found the error to be because my prior part of the script opened this link in a new tab and I had to switch to a different window. The code you have is correct and working – Prem P. Aug 19 '22 at 22:57
0

The desired <option> element,

<optgroup label="mp3">
    <option data-format="mp3" value="128">128kbps (4.18 MB) </option>
</optgroup>

is within it's respective ancestor <optgroup>.


Solution

To click select the desired option you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:

  • Using xpath:

    driver.get('https://yt5s.com/en133?q=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSBjQ9tuuTJQ')
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='formatSelect']"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='formatSelect']//optgroup[@label='mp3']//option[@data-format='mp3']"))).click()
    
  • Browser Snapshot:

optgroup

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352