excelvbaselenium-webdriverxpathselenium-edgedriver

Need help working with elements in a table that have a dynamic xpath Selenium VBA


Using Edge chrome for my browser, selenium, and visual basic. I have a web table that I am trying to iterate through the rows. The problem I have is part of the element name is dynamic.

So for my current edge session the xpath on my first three rows of data in column one are:

//*[@id="content_ctl03_ctl00_G0_G10_G12_BC_e0149528_91fd_45d4_9c23_7b4df75a9207"]/tr[2]/td[1]/div/span
//*[@id="content_ctl03_ctl00_G0_G10_G12_BC_e0149528_91fd_45d4_9c23_7b4df75a9207"]/tr[3]/td[1]/div/span
//*[@id="content_ctl03_ctl00_G0_G10_G12_BC_e0149528_91fd_45d4_9c23_7b4df75a9207"]/tr[4]/td[1]/div/span

Open a different browser session, it could be something like this:

//*[@id="content_ctl03_ctl00_G0_G10_G12_BC_d42b9044_d0bd_4a28_98b2_0631ffd0618c"]/tr[2]/td[1]/div/span
//*[@id="content_ctl03_ctl00_G0_G10_G12_BC_d42b9044_d0bd_4a28_98b2_0631ffd0618c"]/tr[3]/td[1]/div/span
//*[@id="content_ctl03_ctl00_G0_G10_G12_BC_d42b9044_d0bd_4a28_98b2_0631ffd0618c"]/tr[4]/td[1]/div/span

So this might work for today to iterate through the rows of the table... but since this part of the XPath changes, its only temporary. .....G10_G12_BC_836efe7a_d391_42e4_99da_70ca92d784fb']/tr.......

D.FindElementByXPath("//*[@id='content_ctl03_ctl00_G0_G10_G12_BC_836efe7a_d391_42e4_99da_70ca92d784fb']/tr[" & i & "]/td[1]").Click

I'm not sure if my syntax is wrong, but I tried using XPath starts with and contains, but this gives me an error 32 InvalidSelectorError.

Set table_element = D.FindElementByXPath("//*[starts-with(@id, 'content_ctl03_ctl00_G0_G10_G12_BC')] and contains(@id, 'tr[" & i & "]/td[1]/div/span')")

I couldn't get anything like this to work either. Get Run-time error 438 Object not supported

Set table_element = D.FindElementByXPath("//*[starts-with(@id, 'content_ctl03_ctl00_G0_G10_G12_BC')]")
Set elem = D.table_element.FindElementByXPath("//*[contains(@id, 'tr[" & i & "]/td[1]/div/span')]")

Solution

  • You got your brackets wrong on your second expression. Try this

    D.FindElementByXPath("//*[starts-with(@id, 'content_ctl03_ctl00_G0_G10_G12_BC')]/tr[" & i & "]/td[1]").Click
    

    Append a /div/span if necessary.