在VB中,如何使用IndexOf函数查找第二次出现的东西

问题描述 投票:0回答:1

我正在编写一个从网站获取HTML代码的函数,查看要从中提取一些信息然后提取它的span class的名称。我要添加到函数中的其他参数之一是一个数字,该数字指定要搜索的span class(无论是第一次出现,第二次出现还是第三次出现,等等)

[我已经使函数的主要部分起作用(找到span class并提取了它的信息),但是我也想使“出现”部分起作用。

这是我的代码:

Function RetrieveClass(ByRef URL, ByRef ClassToRetrieve, ByRef ClassIndex)
        Const QUOTE = """"

        'Loading the website's HTML code and storing it in a HTML as a string:
        Dim Client As New WebClient
        'URL = "https://jisho.org/search/%E5%8F%AF%E6%84%9B%E3%81%84" 'used to test on the 可愛い page

        Dim HTML As String = Client.DownloadString(New Uri(URL))

        'Used to debug:
        Console.WriteLine(HTML)
        Console.WriteLine("URL: " & URL)

        Dim SnipIndex As Integer = HTML.IndexOf("class=" & QUOTE & ClassToRetrieve) 'Start of the snip, this will look for the class name, example: <span class="meaning-meaning">cute; adorable; charming; lovely; pretty</span>

        If SnipIndex = -1 Then
            Return ("Error: |" & "span class=" & QUOTE & ClassToRetrieve & "| Not Found")
        End If
        Dim Snip As String = Mid(HTML, SnipIndex + 10 + ClassToRetrieve.length, 50)
        SnipIndex = Snip.IndexOf("<")
        Snip = Left(Snip, SnipIndex)

        Console.WriteLine("SnipEnd: " & SnipIndex)
        Console.WriteLine("Snip: " & Snip)




        Console.ReadLine()
        Return (Snip)
    End Function

某些情况:我正在尝试创建一个从日语词典中获取定义和更多内容的网络抓取工具,这将有助于我的语言学习。

如果你看,Dim SnipIndex As Integer = HTML.IndexOf("class=" & QUOTE & ClassToRetrieve)是找到您要搜索的类的行。我想要的是IndexOf函数来搜索第二次出现的span class

谢谢

vb.net web-scraping console-application webclient indexof
1个回答
0
投票

我建议使用一个简单的for循环并运行n次。 (搜索第n个外观)在循环中调用indexOf(string,number),您可以从上一次运行索引中获取数字+字符串长度。这样,第二次循环运行,它将在第一次出现后开始搜索。等等。您可以简单地将索引保存在变量中,然后使用该变量来计算从哪里开始下一个搜索。在循环之前用0初始化变量...

也许有更好的方法可以做到这一点,但这肯定可以。

© www.soinside.com 2019 - 2024. All rights reserved.