vb.net - 有没有办法从网页中检索一些文本到 VB 中的文本框?
问题描述
我正在努力做到这一点,以便我可以在表单中使用多个文本框来显示来自特定网页的信息。例如,是否有一种方法可以通过单击 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?
推荐阅读
- javascript - 用于在 HTML 上为 Web 应用程序实现 PowerPoint 查看器的选项(使用提供的 i-frame 标签嵌入除外)
- c# - BLOB 触发的 Azure 函数中的可选变量
- javascript - 输入字段的React Bootstrap表单样式
- swift - 如何使用协议来表达这个`map`函数
- html - 关闭编译器未检测到脚本标签内的 json
- python - 熊猫中的多级标题问题
- python - 如何在 Keras ImageDataGenerator 中应用 OpenCV 颜色图转换?
- r - 在长格式数据框中标准化日期
- android - Flutter:ios OK,android在启动时崩溃而没有错误
- bash - 与 pre npm 脚本一起使用时如何传递 `--`