首页 > 解决方案 > VB:将特定 HTML 标记中的文本拉入文本框

问题描述

我正在尝试编写一个需要从特定标签中提取文本的 VB.Net 应用程序:

<span data-reactid="85">172,890,000</span>

然后将找到172,890,000的文本输入到表单上的文本框中。

Textbox1中,您输入要搜索的股票代码。

“TTM - 总收入”的数据将始终保存在:

<span data-reactid="85">172,890,000</span>标签。无论您检查的库存是多少。

RichTextBox1, 是下载的 url 源代码。

TextBox2是它拉“TTM”的地方。我可能会将其更改为标签,因为它是一个常量值。我不能将数字放入变量中,因为它会因公司而异,即输入的值TextBox1

TextBox3将显示我真正需要的价值。在172,890,000举行的

<span data-reactid="85">172,890,000</span>标签。

我想知道如何在 中搜索字符串RichTextBox1,并在字符串末尾拉出接下来的 7 个字符,如果这样可行?

到目前为止,我的代码是:

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim Source As String
        Dim ttm1 As String
        Dim ttmrev As String

        Source = New System.Net.WebClient().DownloadString("https://finance.yahoo.com/quote/" + TextBox1.Text + "/financials?p=" + TextBox1.Text)
        ttm1 = <span data-reactid="65">ttm</span>
        ttmrev = <span data-reactid="85"></span>

        RichTextBox1.Text = Source


        If RichTextBox1.Find(ttm1) Then

            TextBox2.Text = "ttm".ToUpper

        End If

    End Sub

End Class

标签: vb.netweb-scrapingyahoo-finance

解决方案


像往常一样在编码中,总是有很多方法可以完成相同的最终结果。一种方法是使用正则表达式。

例如:

Imports System.Text.RegularExpressions

Sub Main

    ' In place of a static string here, place the exact line you want to search instead.
    Dim str As String = "<span data-reactid=""85"">172,890,000</span>"

    ' Search for the match
    showMatch(str, "(\d+),?(\d+),?(\d+)")

End Sub

Sub showMatch(ByVal text As String, ByVal expr As String)
    
    ' Make sure you're expression looks the way you want it
    Debug.WriteLine("The Expression: " + expr)
    
    ' Declare the variable and do the regex match
    Dim mc As MatchCollection = Regex.Matches(text, expr)
    Dim m As Match

    ' Handle the result however you wish; for example instead of a loop, since 
    ' there should only be 1 result you could just do
    ' something like: TextBox3.Text = m.ToString()
    For Each m In mc
        Debug.WriteLine(m)
    Next m
    
End Sub

上面的正则表达式将找到任何匹配的数字,例如:

172,890,000
890,000
000
2,80,000

etc.

另一种选择可能是使用WebBrowser控件,将源提取到其中,然后innerHtml根据需要使用。


推荐阅读