首页 > 解决方案 > 有没有办法从网页中检索一些文本到 VB 中的文本框?

问题描述

我正在努力做到这一点,以便我可以在表单中使用多个文本框来显示来自特定网页的信息。例如,是否有一种方法可以通过单击 Visual Basic 中的按钮将这个问题的标题检索到变量中?

标签: vb.net

解决方案


这并不难,但您必须查看源页面并识别元素。

在格式良好的页面中,通常 div 元素具有标签 ID,但通常它们没有,因此您必须通过属性名称来获取 - 通常您可以使用相关 div 的类名。

所以,为了抢标题,你质疑这篇文章的文字?

这有效:

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

输出:

(第一部分是标题问题)

Is there a way to retrieve some text from a webpage to a textbox in VB?

(第二部分是问题文本)

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?

推荐阅读