Skip to content

🕷️ The BEST Web Scraping framework that handles everything from a single request to a full-scale crawl! Don't be shy, join here: https://discord.gg/EMgGbDceNQ and follow here for daily tips and tricks: https://x.com/Scrapling_dev

Rework Selectors generation

Karim shoair3d4b427168b7
diff --git a/scrapling/core/mixins.py b/scrapling/core/mixins.py
index e83eaa4..8b46f24 100644
--- a/scrapling/core/mixins.py
+++ b/scrapling/core/mixins.py
@@ -4,7 +4,7 @@ class SelectorsGeneration:
Trying to generate selectors like Firefox or maybe cleaner ones!? Ehm
Inspiration: https://searchfox.org/mozilla-central/source/devtools/shared/inspector/css-logic.js#591"""
- def __general_selection(self, selection: str = 'css') -> str:
+ def __general_selection(self, selection: str = 'css', full_path=False) -> str:
"""Generate a selector for the current element.
:return: A string of the generated selector.
"""
@@ -20,10 +20,11 @@ class SelectorsGeneration:
else f"[@id='{target.attrib['id']}']"
)
selectorPath.append(part)
- return (
- " > ".join(reversed(selectorPath)) if css
- else '//*' + "/".join(reversed(selectorPath))
- )
+ if not full_path:
+ return (
+ " > ".join(reversed(selectorPath)) if css
+ else '//*' + "/".join(reversed(selectorPath))
+ )
else:
part = f'{target.tag}'
# We won't use classes anymore because I some websites share exact classes between elements
@@ -60,15 +61,29 @@ class SelectorsGeneration:
)
@property
- def css_selector(self) -> str:
+ def generate_css_selector(self) -> str:
"""Generate a CSS selector for the current element
:return: A string of the generated selector.
"""
return self.__general_selection()
@property
- def xpath_selector(self) -> str:
+ def generate_full_css_selector(self) -> str:
+ """Generate a complete CSS selector for the current element
+ :return: A string of the generated selector.
+ """
+ return self.__general_selection(full_path=True)
+
+ @property
+ def generate_xpath_selector(self) -> str:
"""Generate a XPath selector for the current element
:return: A string of the generated selector.
"""
return self.__general_selection('xpath')
+
+ @property
+ def generate_full_xpath_selector(self) -> str:
+ """Generate a complete XPath selector for the current element
+ :return: A string of the generated selector.
+ """
+ return self.__general_selection('xpath', full_path=True)
diff --git a/tests/parser/test_general.py b/tests/parser/test_general.py
index 6edfced..074ad40 100644
--- a/tests/parser/test_general.py
+++ b/tests/parser/test_general.py
@@ -169,8 +169,8 @@ class TestParser(unittest.TestCase):
def test_selectors_generation(self):
"""Try to create selectors for all elements in the page"""
def _traverse(element: Adaptor):
- self.assertTrue(type(element.css_selector) is str)
- self.assertTrue(type(element.xpath_selector) is str)
+ self.assertTrue(type(element.generate_css_selector) is str)
+ self.assertTrue(type(element.generate_xpath_selector) is str)
for branch in element.children:
_traverse(branch)