Home » excel » excel – Extracting changing XPath in Selenium VBA

excel – Extracting changing XPath in Selenium VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m finding it difficulty in extracting the ( changing) XPath text in the final result page.
This website : http://dgftcom.nic.in/licasp/IecDenQuery.asp
Few IEC sample Codes are

  1. 0504057006 —> This yields result such as FIRM name
  2. 0504057007 —> This yields Invalid IEC code message
  3. 0504057006
  4. 0504057007
  5. 0504057006

    Option Explicit
    
    Public Sub EntityList()
    
    Dim bot As WebDriver
    Dim count As Long
    
    Set bot = New WebDriver
    bot.Start "Chrome"
    count = 1
    While (Len(Range("A" & count)) > 0)
    
    bot.Get "http://dgftcom.nic.in/licasp/IecDenQuery.asp"
    bot.FindElementByXPath("//input[@type='text'][@name='IEC']").SendKeys Range("A" & count)
    bot.FindElementByXPath("//input[@type='submit'][@name='B1']").Click
    
    Range("B" & count) = bot.FindElementByXPath("/html/body/table[2]/tbody/tr/td/font/strong").Text
    'Range("B" & count) = bot.FindElementByXPath("//table/tbody/tr[1]/td[1]").Text
    
    bot.Wait 1000
    
    count = count + 1
    Wend
    bot.Quit
    End Sub
    

The issue here is, when the next IEC code is entered, there is a change in the XPath, and this is where the whole code ends abruptly.

How to&Answers:

Try this following XPath.

//font[contains(.,'IEC :')]

Code:

Range("B" & count) = bot.FindElementByXPath("//font[contains(.,'IEC :')]").Text

Answer:

There are one of two combinations based on whether results table has results. You can use css Or syntax. Should be faster than xpath

Range("B" & count) = bot.FindElementByCss("table td, table + font").Text