VB Httpwebresponse获取内容

时间:2015-06-12 11:32:32

标签: vb.net httpwebresponse

在以下网页上,我想在我的listbox1中获取youtube视频的所有标题

        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))

然而,使用这段代码我得到了标题,但也有很多其他的东西......

2 个答案:

答案 0 :(得分:1)

YouTube提供了API,这可能是获取此信息的更好方式。您要进行的具体通话记录在此处:https://developers.google.com/youtube/v3/docs/search/list

要使用YouTube API,您需要创建API密钥。这可以从Google developers console完成。获得密钥后,您可以拨打YouTube电话来搜索视频,获取视频信息等

使用您的代码作为基础,您可以使用以下内容:

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

q参数指定搜索查询。这将获得您搜索的前50个匹配项,并将它们放入您的下拉列表中。

答案 1 :(得分:0)

如果您想坚持使用正则表达式,请尝试以下

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

然而,专用API更清晰