On the following webpage I'd like to get all the titles of youtube videos in my listbox1
Dim webRequest As WebRequest = webRequest.Create("https://www.youtube.com/results?q=test")
Dim webresponse As WebResponse = webRequest.GetResponse()
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(webresponse.GetResponseStream())
Dim youtube As String = sr.ReadToEnd
Dim r As New System.Text.RegularExpressions.Regex("title="".*""")
Dim matches As MatchCollection = r.Matches(youtube)
For Each itemcode As Match In matches
ListBox1.Items.Add(itemcode.Value.Split("""").GetValue(1))
However with this code I get the titles but also a bunch of other stuff...
YouTube provides an API which might be a better way to get this information. The specific call you want to make is documented here: https://developers.google.com/youtube/v3/docs/search/list.
In order to use the YouTube API you will need to create an API key. This can be done from the Google developers console. Once you have a key then you can make calls to YouTube to search videos, get video information etc
Using your code as the basis you could use something along these lines:
Dim url As String = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=test&maxResults=50&key={YOUR-API-KEY}"
Dim webRequest As WebRequest = webRequest.Create(url)
Dim webresponse As WebResponse = webRequest.GetResponse()
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(webresponse.GetResponseStream())
Dim youtube As String = sr.ReadToEnd
Dim r As New System.Text.RegularExpressions.Regex("""title"": "".*""")
Dim matches As MatchCollection = r.Matches(youtube)
For Each itemcode As Match In matches
ListBox1.Items.Add(itemcode.Value.Split(":").GetValue(1).Trim().TrimStart("""").TrimEnd(""""))
Next
The q parameter specifies the search query. This will get the first 50 matches to your search and put them in your drop down list.
If you want to stick with regular expression try the following
Dim r As New System.Text.RegularExpressions.Regex("title=""([^""]*)""")
Dim matches As MatchCollection = r.Matches(youtube)
For Each itemcode As Match In matches
ListBox1.Items.Add(itemcode.Groups(1))
Next
However a dedicated API is cleaner
Related
Please see part of the code used to save response as a string to resultData variable:
Using response As WebResponse = request.GetResponse()
Dim responseStream As IO.Stream = response.GetResponseStream()
Dim sr As New IO.StreamReader(responseStream)
resultData = sr.ReadToEnd()
It works correctly.
I have one case where the output is a binary file. How can I modify this code to save the reponse as a binary ResultData variable?
Thank you in advance for your support.
There is many ways to do that. This one, is one of those. (This one help you also to show the progress)
However (as advice) to monitoring progress there exists better approaches like Async methods etc.
In the example below I’m going to show you how to save e WebRequest as binary data.
Note that, I’m based on your code and what you want, but, as I said before there exists different better approaches.
'here the file you want to save
Dim LocalFilePath As String = "C:\Users\MyUser\Documents\FolderXYZ\yourfileName.extension"
Using reader As IO.Stream = request.GetResponse.GetResponseStream
Using writer As IO.Stream = New IO.FileStream(LocalFilePath, IO.FileMode.OpenOrCreate, IO.FileAccess.ReadWrite)
Dim b(1024 * 2) As Byte
Dim buffer As Integer = b.Length
Do While buffer <> 0
buffer = reader.Read(b, 0, b.Length)
writer.Write(b, 0, buffer)
writer.Flush()
Loop
End Using
End Using
I have a JSON object created using Newtonsoft JObject but I get a bad request error when I try to submit it if any of the properties have spaces, slashes, etc.
updatestring = "date=2/14/2019"
Dim jobjattr As New Newtonsoft.Json.Linq.JObject(
New Newtonsoft.Json.Linq.JProperty("description", "test"),
New Newtonsoft.Json.Linq.JProperty("source", updatestring)
)
Dim jobjdat As New Newtonsoft.Json.Linq.JObject(
New Newtonsoft.Json.Linq.JProperty("type", "synch_log"),
New Newtonsoft.Json.Linq.JProperty("id", "6278042e-ed64-0418-a651-5c574dc4f12b"),
New Newtonsoft.Json.Linq.JProperty("attributes", jobjattr)
)
Dim jobj As New Newtonsoft.Json.Linq.JObject(New Newtonsoft.Json.Linq.JProperty("data", jobjdat))
Dim jsonserializersettings As New Newtonsoft.Json.JsonSerializerSettings
jsonserializersettings.StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeNonAscii
Dim stringReq = Newtonsoft.Json.JsonConvert.SerializeObject(jobj, jsonserializersettings)
Dim byteData As Byte() = System.Text.Encoding.UTF8.GetBytes(stringReq)
httprequest.ContentLength = byteData.Length
Dim postreqstream As System.IO.Stream = .GetRequestStream()
postreqstream.Write(byteData, 0, byteData.Length)
postreqstream.Close()
incoming jobj = {"data":{"type":"synch_log","id":"6278042e-ed64-0418-a651-5c574dc4f12b","attributes":{"description":"test","source":"date=2/14/2019"}}}
after serialzation byteData still = {"data":{"type":"synch_log","id":"6278042e-ed64-0418-a651-5c574dc4f12b","attributes":{"description":"test","source":"date=2/14/2019"}}}
I would expect the / to be escaped.
any text string works fine
I have also tried jsonserializer settings as Default and EscapeHtml but with the same result.
Other characters cause the same eror. "datetoday" posts correctly but "date=today" and "date today" result in a 400 bad request error
The closest answer I have found is that maybe the object is being double escaped but I can't see how that would be.
Thank you everyone. Brian, you led me in the right direction. I failed to mention that it is an API call to SuiteCRM but your question got me thinking to look on the server side and it turns out there is an unresolved bug with the V8 API. I just assumed it was my code.
github bug report
I am trying to write a simple app in VB.net to gather information from a website and then have the app email the results to me. The purpose is to gather page counts from a printer when the toner is changed. I have the XPATH of the data I need, but I have not been able to figure out how to use this in VB. (I have very little experience programming).
So far I have the app logging into the printer portal and displaying the webpage that has the information I need. The XPATH for this info is:
//*[#id="contents"]/div[3]/div/table/tbody/tr[1]/td
Can anyone help me extract and parse the number out of this table cell?
Thanks for any help you guys can give!!
you can use streamreader! look ath this example:
Dim inStream As StreamReader
Dim webRequest As WebRequest
Dim webresponse As WebResponse
webRequest = webRequest.Create("YOUR URL TO THE PAGE GOES HERE")
webresponse = webRequest.GetResponse()
inStream = New StreamReader(webresponse.GetResponseStream())
Dim sourcecode As String = inStream.ReadToEnd()
Dim x1 As Integer = sourcecode.IndexOf("<td>Nr. of toner changed:") + 25 '25 is the number of characters in the string to search
Dim x2 As Integer = sourcecode.IndexOf("times </td>") 'what comes right after your search string. has to be unique in the page
dim nuberofchanges as integer = sourcecode.Substring(x1, x2 - x1)
hope this helps! :)
I'm trying to set the user agent for a request with XmlRead. I googled a lot about this and couldn't find the answer. Here is my chunk of code:
Dim RssData As DataSet
Dim Title As String
Dim Url As String
Dim Stream As String
Dim buffer As Integer
RssData = New DataSet()
RssData.ReadXml("http://localhost/user_agent.php")
buffer = 0
For Each RssRow As DataRow In RssData.Tables("entry").Rows
Title = Microsoft.VisualBasic.Left(RssRow.Item("title").ToString, 30)
Stream += Title & vbCrLf
Next
LinkLabel3.Text = Stream
For Each RssRow As DataRow In RssData.Tables("entry").Rows
Title = Microsoft.VisualBasic.Left(RssRow.Item("title").ToString, 30)
Url = RssRow.Item("url").ToString
LinkLabel3.Links.Add(buffer, Title.Length, Url)
buffer = buffer + Title.Length + 2
Next
The part of the code that actually performs the web request is buried pretty deep so you'd have to inherit a bunch of code to do what you asked for. Instead, let me suggest a different path, download the XML on your own with code that's easy to set that header, and then load that into the dataset. The WebClient class lets you set arbitrary headers and has a simple DownloadString method. Once you've got that you can wrap it in a MemoryStream and pass that into ReadXml(). (I couldn't find a way to read the XML as a string, that's why I was forced to read it as Stream.)
''//Will hold our downloaded XML
Dim MyXml As String
''//Create a webclient to download our XML
Using WC As New System.Net.WebClient()
''//Manually set the user agent header
WC.Headers.Add("user-agent", "your user agent here")
''//Download the XML
MyXml = WC.DownloadString("http://localhost/user_agent.php")
End Using
''//Create our dataset object
Dim RssData As New DataSet()
''//There is no direct method to load XML as a string (at least that I could find) so we will
''// convert it to a byte array and load it into a memory stream
Dim Bytes As Byte() = System.Text.Encoding.UTF8.GetBytes(MyXml)
Using MS As New System.IO.MemoryStream(Bytes)
''//Load the stream into the reader
RssData.ReadXml(MS)
End Using
''//Your code continues normally here
Hi i am collecting a lot of information from different websites and putting them together for personal use.
there is a rss feed link.
http://picasaweb.google.com/data/feed/base/all?alt=rss&kind=photo&access=public&filter=1&q=waldorf+hilton&hl=en_US
How can i use it? in case of html i just take them and assign them to literals .But how can i display this .
Here is my code..
Dim rssFeed As HttpWebRequest = DirectCast(WebRequest.Create("http://picasaweb.google.com/data/feed/base/all?alt=rss&kind=photo&access=public&filter=1&q=waldorf+hilton&hl=en_US"), HttpWebRequest)
Dim rssData As DataSet = New DataSet()
rssData.ReadXml(rssFeed.GetResponse().GetResponseStream())
Dim Title, Description As String
Dim channelItems As Object() = rssData.Tables(2).Rows(0).ItemArray
Dim titleColumn As Integer = rssData.Tables(2).Columns("title").Ordinal
Dim descriptionColumn As Integer = rssData.Tables(1).Columns("description").Ordinal
Title = channelItems.GetValue(titleColumn).ToString()
Description = channelItems.GetValue(descriptionColumn).ToString()
Repeater1.DataSource = rssData.Tables(2)
Repeater1.DataBind()
Thank you
Are you trying to do this on the web page or inside a vb.net application?
For a webpage: Parse RSS with jQuery
For vb.net, here's one solution: http://www.go4expert.com/forums/showthread.php?t=4577