简体   繁体   中英

c# copy html links from webbrowser and write it in textfile

i want to incorporate function of copying particular links from webbrowser and write it in textfile when the user clicks the button. please help me, this is the function I wrote :

public void grabLink()
        {
            HtmlElementCollection links = webBrowser3.Document.Links ;

            foreach (HtmlElement  link in links)
            {
                if (link.InnerHtml.Contains("register"))
                {
                    using (TextWriter tw = new StreamWriter("link.tnx"))
                    {
                        tw.WriteLine(link.InnerHtml);
                    }
                }

            }
}

 private void button1_Click(object sender, EventArgs e)
        {
            grabLink();
        }

The link I want to copy is like

<a target="_blank" title="Accept" href="https://www.google.com/url?q=https%3A%2F%2Fregister.mig33.co…gmail.com&sa=D&sntz=1&usg=AFQjCNE1sLh2qmw-nEfj3exP8au_3dw3Kg">

    Sign Up Now For Free.

</a>

suggestions and advice will be highly appreciated.

Posting our comment discussion as an answer in case it's useful to anyone else.

You need to use link.OuterHtml to capture the entire output. You're also matching the wrong string (per your link example).

You're also creating a new StreamWriter each time through the loop. This will cause you to only output the last link on the page. Try this:

public void grabLink()
{
    HtmlElementCollection links = webBrowser3.Document.Links ;

    using (TextWriter tw = new StreamWriter("link.tnx"))
    {
        foreach (HtmlElement  link in links)
        {
            if (link.InnerHtml.Contains("Sign Up"))
            {
                tw.WriteLine(link.OuterHtml);
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM