C# SELENIUM – How to read elements of a web page by mentioning a keyword

Question:

I'm creating a Bot that searches a word on google and writes in a txt file all the links found in the search

I'm currently trying to find a keyword on the search result page, store the links containing that keyword in a variable and save it in the txt:

 string mencoesDaPalavra =  Driver.FindElements(By.PartialLinkText("Palavra a pesquisar")).ToString();

After "capturing" the links that contain the word I'm trying to write to the file like this:

StreamWriter file = new StreamWriter("new.txt");
        file.Write(mencoesDaPalavra);
        file.Close();

My attempt was not successful, the line written in the file does not match what I'm looking for… how could I do it?

line recorded in the file:

new.txt = "System.Collections.ObjectModel.ReadOnlyCollection`1[OpenQA.Selenium.IWebElement]"

Answer:

I'm not sure I understand your problem…

Drop the result of your findElements into a collection and do a for each on it.

In each item (a) of the collection use the GetAttribute("href") to get the link

I'll do a different way to get the elements, but you can use it your way. Then say if it worked, or I traveled. Haha

    var colEl = driver.findElements(By.Xpath("//a")).Where(el => el.Text.contains(palavraPesquisa));

    StreamWriter file = new StreamWriter("new.txt");

    foreach (var link in colEl)
            {
                file.Write(link.GetAttribute("href"));
                file.Close();
            }
Scroll to Top
AllEscort