【问题标题】:VB Httpwebresponse get contentVB Httpwebresponse 获取内容
【发布时间】:2015-06-12 11:32:31
【问题描述】:

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

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

但是,通过这段代码,我得到了标题,还有一堆其他的东西......

【问题讨论】:

  • 您的代码不完整...如果您向我们展示“其他内容”也很棒。
  • YouTube 有一个 API,您可以使用它来搜索视频并获取标题和其他信息,而无需抓取 HTML 页面。 developers.google.com/youtube/v3
  • @theduck 太好了,会看看!
  • 这是您想要的特定电话:developers.google.com/youtube/v3/docs/search/list。您需要使用 Google 控制台为自己创建一个 API 密钥,然后您可以进行以下调用:googleapis.com/youtube/v3/…{YOUR_API_KEY},您将获得格式良好的 JSON。
  • @theduck 感谢您的所有意见。使用 API 需要 C#?

标签: vb.net httpwebresponse


【解决方案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 个匹配项并将它们放入您的下拉列表中。

【讨论】:

  • 很棒的伙伴,它正在工作,但在引号中得到结果。谢谢你的帮助:)
  • 我很难通过“”获得结果。你能再帮忙吗?非常感谢。
  • 标题中包含引号“是否存在问题?例如说“你好”
  • 是的,这样,我的列表框中的标题会像“Youtube 视频标题”一样。
  • OK - 已更新代码来处理这个问题(如果我理解正确的话)。理想情况下,您将使用 JSON 解析器而不是 Regex 处理返回的 JSON,但这将完成这项工作。
【解决方案2】:

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

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 更简洁

【讨论】:

  • 感谢您的回复,但是这给了我相同的结果。
  • 所以你得到的标题比你想要的多?
  • 我得到了标题,但还有其他不需要的东西。
  • 然而,在 title="" 字符串中的东西并不是真正的视频标题。只是为了理解
  • 我不怀疑你已经理解了,我只是想知道“其他东西”的含义。当我粘贴你的代码时,我得到了很多文本,可能是因为正则表达式 .* 也匹配双引号字符。我以为你想限制比赛
猜你喜欢
  • 1970-01-01
  • 2015-06-03
  • 2011-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多