Marc Intes
Marc Intes

Reputation: 737

VB.net extract links from google-search using HtmlAgilityPack

I have now updated my code as a test I want to list all URLs that has the word index.php but it also displays other things.

Here is my working code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim webClient As New System.Net.WebClient
    Dim WebSource As String = webClient.DownloadString("http://www.google.com/search?lr=&cr=countryCA&newwindow=1&hl=fil&as_qdr=all&biw=1366&bih=667&tbs=ctr%3AcountryCA&q=index.php&oq=index.php&gs_l=serp.12..0l10.520034.522335.0.525032.9.9.0.0.0.0.497.3073.1j1j2j0j5.9.0....0...1c.1.25.serp..5.4.884.J4smY262XgY")
    RichTextBox1.Text = WebSource

    ListBox1.Items.Clear()


    Dim htmlDoc As New HtmlAgilityPack.HtmlDocument()
    htmlDoc.LoadHtml(WebSource)

    For Each link As HtmlNode In htmlDoc.DocumentNode.SelectNodes("//cite")

        If link.InnerText.Contains("index.php") Then
            ListBox1.Items.Add(link.InnerText)
        End If

    Next

End Sub

expected output should only be websites that has index.php on it, like this:

http://www.site1.com/index.php
http://www.site2.com/index.php
http://www.site3.com/index.php
http://www.site4.com/index.php
http://www.site5.com/index.php

But the problem is it only stops until index.php other parts of the link are not included.

for example the complete url is

http://www.site5.com/index.php?test_test=test&test

the program only displays

http://www.site5.com/index.php

or it would have broken dots like

http://www.site5.com/index.php...test....test

Upvotes: 0

Views: 4380

Answers (1)

Damith
Damith

Reputation: 63105

I would use Html Agility Pack to extract the links as below

Dim links As New List(Of String)()
Dim htmlDoc As New HtmlAgilityPack.HtmlDocument()
htmlDoc.LoadHtml(WebSource)
For Each link As HtmlNode In htmlDoc.DocumentNode.SelectNodes("//a[@href]")
    Dim att As HtmlAttribute = link.Attributes("href")
    If att.Value.Contains("/forums/") Then
        links.Add(att.Value)
    End If
Next

if it is google search result try something like below

For Each link As HtmlNode In htmlDoc.DocumentNode.SelectNodes("//cite")
    If link.InnerText.Contains("index.php") Then
        links.Add(link.InnerText)
    End If
Next

Upvotes: 1

Related Questions