I'm trying to access the select element on this page: https://yt5s.com/en133?q=https://www.youtube.com/watch?v=SBjQ9tuuTJQ
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']"}
What am I doing wrong?
CodePudding user response:
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();
CodePudding user response:
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://www.youtube.com/watch?v=SBjQ9tuuTJQ') 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']//option[@data-format='mp3']"))).click()
Browser Snapshot: