Is there a way to retrieve some text from a webpage to a textbox in VB? - vb.net

I'm trying to make it so I can have several text boxes in my form show pieces of information from a specific webpage. For example, would there be a way I would be able to retrieve the title of this question to a variable with the click of a button in Visual Basic?

It not hard but you have to look at the source page, and identify the elements.
In nicely formed pages, usually the div elements have a tag ID, but often they don't, so you have to grab say by a attribute name - often you can use the class name of the div in question.
So, to grab the Title, and you question text of this post?
This works:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim xDoc As New Xml.XmlDocument
Dim strURL As String = "https://stackoverflow.com/questions/55753982"
Dim xWeb As New WebBrowser
xWeb.ScriptErrorsSuppressed = True
xWeb.Navigate(strURL)
Do Until xWeb.ReadyState = WebBrowserReadyState.Complete
Application.DoEvents()
Loop
Dim HDoc As HtmlDocument = xWeb.Document
Debug.Print(HDoc.GetElementById("question-header").FirstChild.InnerText)
Debug.Print(FindClass(HDoc, "post-text"))
End Sub
Function FindClass(Hdoc As HtmlDocument, strClass As String) As String
' get all Divs, and search by class name
Dim OneElement As HtmlElement
For Each OneElement In Hdoc.GetElementsByTagName("div")
If OneElement.GetAttribute("classname") = strClass Then
Return OneElement.InnerText
End If
Next
' we get here, not found, so return a empty stirng
Return "not found"
End Function
OutPut:
(first part is title question)
Is there a way to retrieve some text from a webpage to a textbox in VB?
(second part is question text)
I'm trying to make it so I can have several text boxes in my form show pieces of
information from a specific webpage. For example, would there be a way I would be
able to retrieve the title of this question to a variable with the click of a button
in Visual Basic?

Related

VB.NET 2019 How to populate a Tag Property on a dynamic ToolstripmenuItem

I am struggling to populate a tag property on a dynamically created sub menu which I have created. I have a text file that contains a number of radio station names, BBC1, BBC2, BBC3 for example, as well as the associated stream addresses for said stations. I am able to pull in the names and apply it to the submenu. They appear fine. I can click on the submenus, and the sender() variable confirms the station names correctly. My problem is that I cannot get the Tag property for each sub menu/radio station, to store the stream address. The code gets the radio title cleans the code and inserts it into the RadioStreamsToolStripMenuItem.DropDownItems.Add(station_name) and all is fine. The code then gets the Stream address and inserts it here RadioStreamsToolStripMenuItem.Tag.ToString(). I can tell that it is wrong, but how do I go about ensuring the correct stream goes into the correct radio Tag property. Im very new to this so please be gentle, its just a little hobby.
'======================================================================
'Aquires Radio name and creates a dropdown sub menu within RadioStreams
'======================================================================
Do While (Not line Is Nothing)
If line.StartsWith("#") Then
station_name = Replace(line, "#", "")
Dim x = RadioStreamsToolStripMenuItem.DropDownItems.Add(station_name)
AddHandler x.Click, AddressOf ToolMenuItem_Click
'===================================================
'Aquires Radio Stream to add to the Tag property for each new station
'===================================================
ElseIf line.StartsWith("#") Then
Dim station_stream As String = Replace(line, "#", "")
'The following just checks if the data has gone into the correct place
For Each Myitem As ToolStripItem In RadioStreamsToolStripMenuItem.DropDownItems
If Myitem.Text = station_name Then
MsgBox("MyItems " & Myitem.ToString())
Me.Tag = station_stream
End If
Next
You could use a Dictionary to store the stations a stream addresses. Dictionary lookups are very fast.
I assumed from your code that your text file looks like this
#BBC1
#BBC1streamAddress
#BBC2
#BBC2streamAddress
#BBC3
#BBC3streamAddress
I looped through the lines of the file assigning the trimmed keys and values to the dictionary. Then looped through the dictionary filling the menu. When the user clicks a menu item we get the text of the item and search the dictionary for the correct stream address.
Private RadioDictionary As New Dictionary(Of String, String)
Private Sub OPCode()
Dim lines = File.ReadAllLines("Radio.txt")
For i = 0 To lines.Length - 1 Step 2
RadioDictionary.Add(lines(i).Trim("#"c), lines(i + 1).Trim("#"c))
Next
For Each item In RadioDictionary
Dim x = RadioStreamsToolStripMenuItem.DropDownItems.Add(item.Key)
AddHandler x.Click, AddressOf ToolMenuItem_Click
Next
End Sub
Private Sub ToolMenuItem_Click(sender As Object, e As EventArgs) Handles ToolMenuItem.Click
Dim station = DirectCast(sender, ToolStripDropDownItem).Text
Dim stream = RadioDictionary(station)
End Sub

Check if data exist in file

I need help. I want to check if user exists by entering their ic number and I want to display another rest of their data by using file in visual basic. Unfortunately, an error occurs while doing that. I need help. If the user exists, then It will display automatically name, email, address and so on but if a user doesn't exist, then it shows message box. Here I attached the image of the display screen and the code. Please help me. Thank you.
Public Class Form1
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim userFile As String = "C:\Users\HP\Desktop\userdata.txt"
Dim inputFile As String
If System.IO.File.Exists(userFile) = True Then
Dim objReader As New System.IO.StreamReader(userFile)
Dim intIc As Integer
Dim intCount As Integer = 0
Dim strName As String
Dim strEmail As String
Dim intPhoneNum As String
Dim strAdd1 As String
Dim strAdd2 As String
Dim intPostcode As String
Dim strState As String
Do While objReader.Peek() <> -1
intIc(intCount) = Convert.ToInt64(objReader.ReadLine())
If (intIc(intCount).Convert.ToInt64(objReader.ReadLine())) Then
strName(intCount) = objReader.ReadLine()
strEmail(intCount) = objReader.ReadLine()
intPhoneNum(intCount) = Convert.ToInt32(objReader.ReadLine())
strAdd1(intCount) = objReader.ReadLine()
strAdd2(intCount) = objReader.ReadLine()
intPostcode(intCount) = Convert.ToInt32(objReader.ReadLine())
strState(intCount) = objReader.ReadLine()
lblName.Text = strName
lblEmail.Text = strEmail
lblNum.Text = intPhoneNum
lblAdd1.Text = strAdd1
lblAdd2.Text = strAdd2
lblPostcode.Text = intPostcode
lblState.Text = strState
objReader.Close()
Else
MessageBox.Show("User Does Not Exist")
End If
intCount = intCount + 1
Loop
Else
MessageBox.Show("File Does Not Exist")
End If
End Sub
End Class
Your task, the easy way:
make a new project
add a DataSet to this new project
open the DataSet, in the properties call it something sensible
Right click the surface, add a new datatable, name it Person
Right click the datatable, add a column, name it IC. Right click, add column, name it Name. Keep going until you added all the fields you want to track(email,phone,address1 etc)
save the DataSet
open the form
show the datasources window (view menu.. other windows)
expand the nodes til you can see Person
click the drop down next to Person, switch from DataGridview to Details
drag Person onto the form. Text boxes, labels etc appear. In the tray at the bottom more things appear
add a textbox to the form and call it searchTextBox
add a search button to the form, double click it, add this line of code to the click handler:
personBindingSource.Filter = '[ic] LIKE '" & searchTextBox.Text & "'"
If personBindingSource.Count = 0 Then MessageBox.Show("No records")
double click the form background to add a form load event handler, put this line of code:
If IO.File.Exists("data.xml") Then .ReadXml("data.xml")
switch back to designer, single click the form background and switch to event properties of the form, add a handler to the form closing event:
.WriteXml("data.xml")
That's it, you now have a program that will open, read and fill the DataSet with data from the data.xml file, it will search it when you type something in the ic box, the text boxes use databinding to show values automatically, and when you close the program it will save updates data. The only task now is to load the xml file with data.
When the textboxes were added to the form you should also have seen a bar appear across the top with some left/right controls in and a green plus. Click the green plus, type some data in, click it again, type more data. Navigating back, if you're adding new data, will commit the data. If you're looking at existing data, editing it then navigating will commit it
After you added some data, you can search for existing data using the search box. When you've searched for a single value it should be the only thing shown and the nav will show "1 of 1". To get back to the mode where all data is showing, put a single asterisk in the search box and hit search; it should show the number records in the top bar and you can scroll them with the arrows.
If you already have lots of data in a file, like you use in your question, you can read it in a loop (like you do in your question, except don't use that code exactly cos it has loads of errors) as a one time thing and assign it into the datatable, or you can manipulate it directly into being XML in a text editor. This is easy to do if you have a capable text editor but I'll not offer any particular advice on it in case you don't have a large amount of existing data. Ask a new question if you do

How can I play the first url that I get when I search in youtube with vb.net?

I trying to do a program in vb.net that will search a video on youtube by words and play the first url (the first result) that I will get without waiting to client to choose.
Someone can help me?
I did the search but I dont know how to do that it will play the first video that I will get automatically.
What form you choose to develop this program ? Webform ? Winform?
I assume that the form is winform, then you could use the "WebBrowser" (you can find the "WebBrowser" in the toolbox)
Private Sub openYouTube()
WebBrowser1.Navigate("https://www.youtube.com/?gl=TW")
End Sub
Find the search bar on the youtube (use GetElementByID) and insert the string which you want to search (Use SetAttribute). The ID of the inputbox of youtube search bar is "search" (How to find the ID of any element in a webpage? Target the element and click the right button of mouse, choose "inspect" for Chrome, "inspect element" for IE, it would show the element detail)
Private Sub inputString&SearchIt()
Dim theStringYouWantToSearch as string
WebBrowser1.Document.GetElementById("search").SetAttribute("value", theStringYouWantToSearch)
End Sub
Execute the search (Use InvokeMember("click") to fire the search)
Private Sub executeSearch()
WebBrowser1.Document.GetElementById("search-icon-legacy").InvokeMember("click")
End Sub
Find the first result and record the URL.
This process is more complicated, use GetElementsByTagName to get a collection of result tables, the first result is the first item of this collection. Find the table of first result then loop through all elements of this table, to find the element which id is "thumbnail", and this element has the information of part of URL.
Private Sub findFirstResult()
Dim elemCollection as HtmlElementCollection
Dim firstResultTable as HtmlElement
Dim hrefString as string
Dim resultURL as string
elemcollection = WebBrowser1.Document.GetElementsByTagName("ytd-video-renderer")
firstResultTable = elemCollection.item(0)
For each element as HtmlElement in firstResultTable.All
If element.Id = "thumbnail" then
hrefString = element.GetAttribute("href")
End if
Next
resultURL = "https://www.youtube.com" & hrefString
End Sub
Between every step, you have to wait for the complement of webpage loading, or the program wouldn't find the element. There are several ways to do that, you could do some search for that.

Grab specific part of text from a local html file and use it as variable

I am making a small "home" application using VB. As the title says, I want to grab a part of text from a local html file and use it as variable, or put it in a textbox.
I have tried something like this...
Private Sub Open_Button_Click(sender As Object, e As EventArgs) Handles Open_Button.Click
Dim openFileDialog As New OpenFileDialog()
openFileDialog.CheckFileExists = True
openFileDialog.CheckPathExists = True
openFileDialog.FileName = ""
openFileDialog.Filter = "All|*.*"
openFileDialog.Multiselect = False
openFileDialog.Title = "Open"
If openFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim fileReader As String = My.Computer.FileSystem.ReadAllText(openFileDialog1.FileName)
TextBox.Text = fileReader
End If
End Sub
The result is to load the whole html code inside this textbox. What should I do so to grab a specific part of html files's code? Let's say I want to grab only the word text from this span...<span id="something">This is a text!!!</a>
I make the following assumptions on this answer.
Your html is valid - i.e. the id is completely unique in the document.
You will always have an id on your html tag
You'll always be using the same tag (e.g. span)
I'd do something like this:
' get the html document
Dim fileReader As String = My.Computer.FileSystem.ReadAllText(openFileDialog1.FileName)
' split the html text based on the span element
Dim fileSplit as string() = fileReader.Split(New String () {"<span id=""something"">"}, StringSplitOptions.None)
' get the last part of the text
fileReader = fileSplit.last
' we now need to trim everything after the close tag
fileSplit = fileReader.Split(New String () {"</span>"}, StringSplitOptions.None)
' get the first part of the text
fileReader = fileSplit.first
' the fileReader variable should now contain the contents of the span tag with id "something"
Note: this code is untested and I've typed it on the stack exchange mobile app, so there might be some auto correct typos in it.
You might want to add in some error validation such as making sure that the span element only occurs once, etc.
Using an HTML parser is highly recommended due to the HTML language's many nested tags (see this question for example).
However, finding the contents of a single tag using Regex is possible with no bigger problems if the HTML is formatted correctly.
This would be what you need (the function is case-insensitive):
Public Function FindTextInSpan(ByVal HTML As String, ByVal SpanId As String, ByVal LookFor As String) As String
Dim m As Match = Regex.Match(HTML, "(?<=<span.+id=""" & SpanId & """.*>.*)" & LookFor & "(?=.*<\/span>)", RegexOptions.IgnoreCase)
Return If(m IsNot Nothing, m.Value, "")
End Function
The parameters of the function are:
HTML: The HTML code as string.
SpanId: The id of the span (ex. <span id="hello"> - hello is the id)
LookFor: What text to look for inside the span.
Online test: http://ideone.com/luGw1V

Get HTML element without 'For Each' loop

I've started to do some programming in Visual Basic and I need some help. This might be a simple question but I can't figure this out.
So I have created a web browser and I would like to get the Profile Picture of a person on Facebook and display it on a Picture Box, and also the Name of that person and display it on a TextBox. After that the program should save the picture in a folder on my hard drive.
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
Dim elemCollection As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("img")
Dim fbPath As String = "C:\Users\" + Environment.UserName.ToString + "\Documents\FB Images\"
For Each curElement As HtmlElement In elemCollection
If curElement.OuterHtml.Contains("profilePic img") Then
PictureBox1.ImageLocation = curElement.GetAttribute("src") 'Showing the profile pic in picture box
TextBoxName.Text = curElement.GetAttribute("alt") 'Showing the name in a textbox
Dim NumberOfFiles As Integer = System.IO.Directory.GetFiles(fbPath).Length
Dim bmp As New Bitmap(PictureBox1.Width, PictureBox1.Height)
PictureBox1.DrawToBitmap(bmp, PictureBox1.ClientRectangle)
bmp.Save(System.IO.Path.Combine(fbPath, CStr(NumberOfFiles) + TextBoxName.Text + ".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg)
End If
Next
End Sub
So the program should save the picture with a file name according to the number of files there is in the folder path(e.g '1 George Johnson.jpg'). But what happens, it is saving 5 different images because I guess there are more than one HTML elements that matches those attributes, so the For Each loop brings up more results.
Is there any way to get an HTML element without using this loop and just get a particular element that I want?
If you just want the first time the if statement for the attribute is true , add "Exit For" the line before the End If.