C# SELENIUM - How to read elements of a web page by keyword mention

Asked

Viewed 1,680 times

3

I’m creating a bot that searches a word in google and writes in a txt file all links found in the search

I am currently trying to find a keyword on the search result page, store the links that contain that keyword in a variable and write to 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 unsuccessful, the line recorded in the file does not match what I am searching for.. as I could do ?

line saved in file :

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

  • The method FindElements returns an array of objects (Webelement) and not a string. You need to iterate on this array to get links.

1 answer

1

I’m not sure I understand your problem...

Play the result of your findElements on a Collection and do a for each on it.

On each item (a) of Collection use Getattribute("href") to get the link

I will make a different way to pick up the elements, but you can use it your own way. Then tell me if it worked out, or I did. Rsrs

    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();
            }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.