Skip to content

Commit

Permalink
Add contains to XPathLocator
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
M1troll committed May 27, 2024
1 parent fe8b383 commit 458ba3c
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions pomcorn/locators/base_locators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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)

0 comments on commit 458ba3c

Please sign in to comment.