我正在努力做到这一点,因此我可以在表单中有几个文本框来显示特定网页上的信息。例如,是否可以通过单击Visual Basic中的按钮将这个问题的标题检索为变量?
答案 0 :(得分:0)
这并不难,但是您必须查看源页面并识别元素。
在结构良好的页面中,通常div元素具有标签ID,但通常没有标签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?