c#Seleniumyoutube検索sendkeys

Aug 29 2020

YouTubeで検索したいです。ページが開き、クリックして検索しますが、書き込みに関してエラーが発生します。

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");

回答

1 CoolBots Aug 29 2020 at 14:53

あなたのアプローチにはいくつかの問題があります:

  • 探している要素By.Idは「search-form」ではなく「search」である必要があります
  • youtube.comホームページには「検索」のIDを持つ4つの要素があります
  • 要素にアクセスしているときに、ページが完全に読み込まれない場合があります。の使用WebDriverWaitも正しくありません。

解決:

  • 利用可能になったら、IDが「search」のすべての要素を検索し、入力要素を取得します
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");