get top 10 post in google by selenium in csharp

To get the top 10 search results for a query on Google using Selenium in C#, follow these steps:

  1. Download and install Selenium WebDriver for C# from NuGet.

  2. Create a new Selenium WebDriver instance for your desired web browser:

main.cs
IWebDriver driver = new ChromeDriver();
40 chars
2 lines
  1. Navigate to the Google search page:
main.cs
driver.Navigate().GoToUrl("https://www.google.com/");
54 chars
2 lines
  1. Find the search box element by its name attribute and type in the query:
main.cs
IWebElement searchBox = driver.FindElement(By.Name("q"));
searchBox.SendKeys("your query");
searchBox.Submit();
112 chars
4 lines
  1. Wait for the search results to load and find the list of search result elements:
main.cs
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IList<IWebElement> resultList = wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.CssSelector("div.g")));
196 chars
3 lines
  1. Loop through the list of search result elements and print out the title and URL for each result:
main.cs
for (int i = 0; i < 10; i++)
{
    IWebElement result = resultList[i];
    IWebElement linkElement = result.FindElement(By.TagName("a"));
    string title = linkElement.Text;
    string url = linkElement.GetAttribute("href");

    Console.WriteLine($"{i + 1}. {title}");
    Console.WriteLine($"\t{url}");
}
308 chars
11 lines

Note that this code assumes that the search results are displayed in the normal Google search result format, with each individual result represented by a div element with a class of g. If Google changes its search result format, this code may not work as expected. Additionally, web scraping may be against Google's terms of service, so use it at your own risk.

gistlibby LogSnag