From 8d4f01c8696e96c54de8ad4d756bb8d61fd35807 Mon Sep 17 00:00:00 2001 From: Anton Oboleninov Date: Fri, 24 May 2024 14:51:25 +0700 Subject: [PATCH] Add `contains` to `XPathLocator` There is often a situation when you need to add `[contains(., text)]` to an already ready locator, and for this you have to use `extend_query`. So we decided to put it into a separate method. --- pomcorn/locators/base_locators.py | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/pomcorn/locators/base_locators.py b/pomcorn/locators/base_locators.py index fb9deda..2f28b17 100644 --- a/pomcorn/locators/base_locators.py +++ b/pomcorn/locators/base_locators.py @@ -121,11 +121,15 @@ def __init__(self, query: str): def __truediv__(self, other: XPathLocator) -> XPathLocator: """Override `/` operator to implement following XPath locators.""" - return XPathLocator(query=f"{self.query}/{other.related_query}") + return XPathLocator( + query=f"//{self.related_query}/{other.related_query}", + ) def __floordiv__(self, other: XPathLocator) -> XPathLocator: """Override `//` operator to implement nested XPath locators.""" - return XPathLocator(query=f"{self.query}//{other.related_query}") + return XPathLocator( + query=f"//{self.related_query}//{other.related_query}", + ) def __or__(self, other: XPathLocator) -> XPathLocator: r"""Override `|` operator to implement variant XPath locators. @@ -145,3 +149,19 @@ def __or__(self, other: XPathLocator) -> XPathLocator: def extend_query(self, extra_query: str) -> XPathLocator: """Return new XPathLocator with extended query.""" return XPathLocator(query=self.query + extra_query) + + def contains(self, text: str, exact: bool = False) -> XPathLocator: + """Return new XPathLocator with search on contained text. + + This is shortcut for the commonly used + `.extend_query(f"[contains(., '{text}')])`. + + Args: + text: The text that should be inside the tag. + exact: Specify whether the text being searched must match exactly. + By default, the search is based on a partial match. + + """ + partial_query = f"[contains(., '{text}')]" + exact_query = f"[./text()='{text}']" + return self.extend_query(exact_query if exact else partial_query)