c # Selenium youtube Search sendkeys

Aug 29 2020

Je souhaite effectuer une recherche sur youtube. La page s'ouvre, clique pour rechercher, mais j'obtiens une erreur lors de l'écriture.

OpenQA.Selenium.ElementNotInteractableException: 'element not interactable
var chromeDriverService = ChromeDriverService.CreateDefaultService();
            chromeDriverService.HideCommandPromptWindow = true;
            IWebDriver driver;
            ChromeOptions options = new ChromeOptions();
            options.AddUserProfilePreference("profile.default_content_setting_values.images", 2);
            options.AddArgument("start-maximized");
            options.AddArgument("disable-infobars");
            options.AddArgument("--disable-extensions");
            driver = new ChromeDriver(chromeDriverService, options);
            driver.Navigate().GoToUrl("https://www.youtube.com/");
            IWebElement search = driver.FindElement(By.Id("search-form"));
            search.Click();
            WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 10));
            search.SendKeys("xyz");

Réponses

1 CoolBots Aug 29 2020 at 14:53

Il y a plusieurs problèmes avec votre approche:

  • L'élément que vous recherchez By.Iddoit être "recherche" et non "formulaire de recherche"
  • Il y a 4 éléments sur la page d'accueil de youtube.com qui ont l'identifiant "recherche"
  • La page peut ne pas se charger complètement lorsque vous accédez aux éléments. Votre utilisation de WebDriverWaitest également incorrecte.

Solution:

  • Trouvez tous les éléments avec l'identifiant de "recherche" une fois qu'ils sont disponibles et récupérez l' élément d' entrée :
var chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true;

ChromeOptions options = new ChromeOptions();
options.AddUserProfilePreference("profile.default_content_setting_values.images", 2);
options.AddArgument("start-maximized");
options.AddArgument("disable-infobars");
options.AddArgument("--disable-extensions");
            
var driver = new ChromeDriver(chromeDriverService, options);
driver.Navigate().GoToUrl("https://www.youtube.com/");

// New code - get the input element with id "search" once it's ready            
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(1500));            
var elementsWithSearchID = wait.Until((driver) => driver.FindElements(By.Id("search")));
var search = elementsWithSearchID.Where(e => e.TagName == "input").FirstOrDefault();

// No need to click it - just send text with a `\n`, 
// which simulates typing the text and pressing the enter key
search.SendKeys("Hello\n");