Given a website, our customers will pick a spot on their website and we record an xpath to that location.

Our software is DNS integrated, similar to cloudflare, and we manipulate the origin's html response based on the xpath the customer has chosen.

I am faced with a challenge where if a customer adds new or changed html, even though it visually looks the same, we lose the location of where they originally picked because the xpath does not match up.

How would you have a fallback or maybe a different design for this?

  • maybe add an Id to the selected element before the change?
    – Ewan
    Commented Oct 15, 2020 at 17:57
  • Hey @Ewan! Thanks for the comment, could you explain a little further?
    – ericraio
    Commented Oct 15, 2020 at 18:07
  • what isnt clear?
    – Ewan
    Commented Oct 15, 2020 at 18:13

1 Answer 1


Tools that record XPaths tend to generate extremely specific XPaths. As you have realized, this makes for brittle locators. The challenge with identifying elements in a dynamic structured document, like HTML, is to make the xpath specific enough so unrelated elements are not captured, but general enough so minor changes to the page don't break your application.

Simply put: less is more.

Use HTML attributes to help filter the elements captured by your xpath expression. The tool might give you:


How many aside tags exist on any given page? Probably not many. We can simplify the xpath:


And then what about that div inside the aside? It has a class name that is pretty unique: sidebar-ad

//aside/div[contains(@class, "sidebar-ad")]

As long as that div tag has that class and resides inside an aside tag you should be fine.

Better yet, tell them they need to add specific attributes that your code looks for. Custom data attributes will work fine and validate as HTML:

<div data-yourproduct-sidebar-ad="something useful for your code">

Your xpath can simply be:


That will be just about bullet proof.

You need to get creative and understand xpath expressions. Learn that the tool will give you a brittle expression and that you need to optimize it. Or give your clients some tokens your code looks for in order to do something.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.