2

私はセレンWebドライバーに不慣れで、問題があります

何かをグーグルで検索したところ、結果が表示されました。最初の 5 つの結果に検索されたテキストが含まれているかどうかを確認したいと思います。

例として:

テキスト「selenium webdriver」を検索したい。ここで、最初の 5 つの結果に「selenium webdriver」というテキストが含まれているかどうかを確認したいと思います。

これが私の部分です:

chromeDriver.Navigate().GoToUrl("http://www.google.co.uk");

IWebElement searchText = chromeDriver.FindElement(By.XPath(".//html/body/div[3]/div/div/div[2]/div[2]/div/form/fieldset[2]/div/div/div/table/tbody/tr/td[2]/div/input"));
searchText.SendKeys("selenium webdriver");

IWebElement searchButton = chromeDriver.FindElement(By.Name("btnG"));
searchButton.Click() ;

IWebElement resultingText = chromeDriver.FindElement(By.LinkText("selenium webdriver"));

この行は例外をスローしています:

// IWebElement resultingText = chromeDriver.FindElement(By.LinkText("selenium webdriver"));

誰でもこの問題で私を助けることができますか?

4

4 に答える 4

2

LinkTextロケーターはリンク テキストの正確な一致を検出するため、例外が発生します。したがって、「selenium webdriver」というテキストのみを含むリンクを探します。Google 検索の結果を見ると、完全一致が存在しないため、例外が発生します。

このコードは、検索結果の最初のページに含まれるすべてのリンクを出力します。ここから、これを変更して最初の 5 つをチェックし、条件に一致するテキストが含まれているかどうかを確認できます。

IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://google.com");

IWebElement element = driver.FindElement(By.Id("gbqfq"));
element.SendKeys("selenium webdriver");

// Get the search results panel that contains the link for each result.
IWebElement resultsPanel = driver.FindElement(By.Id("search"));

// Get all the links only contained within the search result panel.
ReadOnlyCollection<IWebElement> searchResults = resultsPanel.FindElements(By.XPath(".//a"));

// Print the text for every link in the search results.
foreach (IWebElement result in searchResults)
{
    Console.WriteLine(result.Text);
}
于 2013-06-26T16:29:23.337 に答える
0

XPath のみを使用する場合は、CSS セレクターを使用することをお勧めします。'fire path' を選択してください。これにより、短く正確な Xpath が生成され、コードに配置されます。そのような長い Xpath の使用は避けてください。

于 2014-02-01T17:22:40.110 に答える
0
  1. ひどい xpath を使用しています。次のようなものを試してください//input[@id='gbqfq']
  2. テキストで何かを検索する場合、レジストリに依存します
  3. 5 つの結果がある場合は、次を使用できます (私は C# に慣れていないため、Python コードを次に示します。理解する必要があります)。

    first_five = driver.find_elements_by_xpath(".//*[@id='rso']//div//h3/a")[:5]     
    #returns the list of first five result links
    for result in first_five:
        assert "selenium webriver" in result.text.lower(), "Result does not contain 'selenium webdriver'" 
        # lower - to get rid off registry troubles
    
于 2013-06-20T09:43:42.023 に答える