Navigate readystate 在未就绪时给出就绪状态

Navigate readystate gives a ready state while not ready

我有打开网站并搜索特定基因的代码(提到的测试示例:AX1、TREM2)。

如果我 运行 代码多次 and/or 更改我正在搜索的基因,它会崩溃:

brow.document.forms("searchForm").elements("query").Value = geneN

导航功能似乎在未准备就绪时给出了就绪状态。

我等了 10 秒,但它似乎跳过了正确的导航。

Sub openprot()

    Dim brow As New SHDocVw.InternetExplorer
    Dim URLp As String
    Dim geneN As String 'name of gene
    Dim HTMLco As HTMLDocument
    Dim allrefs As MSHTML.IHTMLElementCollection
    Dim elink As MSHTML.IHTMLElement
    Dim lol As String
    
    geneN = Application.InputBox("name your gene", "gene") 'try TREM2 or AXL
    
    URLp = "https://www.proteinatlas.org/"
    
    brow.navigate URLp
    Do Until brow.READYSTATE = 4: DoEvents: Loop 'variation tested
    'Do While brow.READYSTATE <> READYSTATE_COMPLETE: DoEvents: Loop
    'Do While brow.Busy: DoEvents: Loop
    'Do Until brow.READYSTATE = READYSTATE_COMPLETE: DoEvents: Loop
    
    brow.document.forms("searchForm").elements("query").Value = geneN
    brow.document.forms("searchForm").elements("searchButton").Click
    
    Set HTMLco = brow.document
    Application.Wait Now + TimeValue("00:00:02")
    Set allrefs = HTMLco.getElementsByTagName("a")
    
    For Each elink In allrefs
        lol = elink.href
        If InStr(1, lol, geneN, 1) > 0 And InStr(1, lol, "tissue", 1) > 0 Then
            elink.Click
            Application.Wait Now + TimeValue("00:00:02")
            brow.Visible = True
            Exit For
        End If
    Next elink
    
End Sub

我发现 IE 并不总是加载页面(例如 404 类型错误) 这将提供就绪状态,但当然页面的所有项目都不存在。

为了颠覆这一点,我加载了页面,直到按照 Tim Williams 的建议,该项目是他们的。 我将它包含在一个循环中,直到页面加载完毕 请小心这个循环,因为循环计数器可能很有用

见下方代码

Dim brow As New SHDocVw.InternetExplorer
Dim URLp As String
Dim GeneB As Object 'button used
Dim geneN As String 'Gene name
Dim HTMLco As HTMLDocument
Dim allrefs As MSHTML.IHTMLElementCollection
Dim elink As MSHTML.IHTMLElement
Dim lol As String
Dim x As Integer

    Set GeneB = ActiveSheet.Buttons(Application.Caller)
    geneN = GeneB.Characters.Text
        x = 0
    URLp = "https://www.proteinatlas.org/"
    Do Until x = 1
        brow.navigate URLp
        Do While brow.READYSTATE <> READYSTATE_COMPLETE: Loop
        If IsObject(brow.document.forms("searchForm")) Then
            x = 1
        End If
    Loop
    brow.document.forms("searchForm").elements("query").Value = geneN
    brow.document.forms("searchForm").elements("searchButton").Click
    
    Set HTMLco = brow.document
    Application.Wait Now + TimeValue("00:00:02")
    Set allrefs = HTMLco.getElementsByTagName("a")
    
    For Each elink In allrefs
    lol = elink.href
        If InStr(1, lol, geneN, 1) > 0 And InStr(1, lol, "tissue", 1) > 0 Then
            elink.Click
        Application.Wait Now + TimeValue("00:00:02")
        brow.Visible = True
        Exit For
        End If
    Next elink