我正在尝试这样做,以便我可以在我的表单中有几个文本框显示来自特定网页的信息片段。 例如,是否有一种方法可以通过单击 Visual Basic 中的按钮将此问题的标题检索到变量中?
这并不难,但你必须查看源页面,并确定元素。
在格式良好的页面中,通常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?