How can I switch iframe using selenium vba?

2019-09-16 14:43发布

问题:

Writing a script in vba using selenium for the purpose of switching iframe when I run it, I get an error: object doesn't support this property. How can I do it if I take the below example as consideration.

Sub HCAD()
    Dim driver As New ChromeDriver

    driver.Get "http://hcad.org/quick-search/"
    driver.Wait 500
    driver.SwitchToFrame (driver.FindElementByTag("iframe"))
End Sub

Here is the script with which i was trying to get the name of the address from the target page. Turn out when i reach there i faced another iframe so end up getting nothing. There is only one name against the address i mentioned in my script.

Sub HCAD()
    Dim driver As New ChromeDriver
    Dim post As Object

    driver.Get "https://public.hcad.org/records/quicksearch.asp"
    driver.Wait 500
    driver.FindElementById("s_addr").Click
    driver.FindElementByName("stnum").SendKeys ("8227")
    driver.FindElementByName("stname").SendKeys ("FINDLAY ST")
    driver.FindElementByXPath("//input[@value='Search']").Click
    driver.Wait 1000

    Cells(1, 1) = driver.FindElementByXPath("/html/body/table/tbody/tr/td/table[5]/tbody/tr[2]/td[1]/table/tbody/tr/th").Text

End Sub

回答1:

little extra good functionality added to your code

btw .. the cells(1,1) line fails

Sub HCAD()

    ' add ref: Selenium Type Library

    Dim driver As New ChromeDriver    ' PhantomJSDriver (this one is for "headless" browsing) 

    driver.Get "https://public.hcad.org/records/quicksearch.asp"
    driver.Wait 500
    driver.FindElementById("s_addr").Click
    driver.FindElementByName("stnum").SendKeys ("8227")
    driver.FindElementByName("stname").SendKeys ("FINDLAY ST")
    driver.FindElementByXPath("//input[@value='Search']").Click
    driver.Wait 1000

    Dim bbb As Object
    Set bbb = driver.TakeScreenshot
    bbb.ToExcel Cells(5, 1)
    Set bbb = Nothing


    Cells(1, 1) = driver.FindElementByXPath("/html/body/table/tbody/tr/td/table[5]/tbody/tr[2]/td[1]/table/tbody/tr/th").Text

    Set driver = Nothing

End Sub


回答2:

According to the suggestion given by @Mathieu Guindon, the solution should be like below (working one).

Sub HandleIframe()
    With New ChromeDriver
        .get "http://hcad.org/quick-search/"
        .SwitchToFrame .FindElementByTag("iframe", timeout:=10000)
        .FindElementById("acct").SendKeys "8227"
        .FindElementByCss("input[value='Search']").Click
    End With
End Sub