Skip to content

Commit

Permalink
Adding empty methods (get/get_all/extract/extract_all)
Browse files Browse the repository at this point in the history
For easy copy-paste from Scrapy/parsel code when needed :)
  • Loading branch information
D4Vinci committed Dec 4, 2024
1 parent 31e838c commit 45e86f5
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
23 changes: 23 additions & 0 deletions scrapling/core/custom_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,16 @@ def clean(self) -> str:
data = re.sub(' +', ' ', data)
return self.__class__(data.strip())

# For easy copy-paste from Scrapy/parsel code when needed :)
def get(self, default=None):
return self

def get_all(self):
return self

extract = get_all
extract_first = get

def json(self) -> Dict:
"""Return json response if the response is jsonable otherwise throw error"""
# Using str function as a workaround for orjson issue with subclasses of str
Expand Down Expand Up @@ -186,6 +196,19 @@ def re_first(self, regex: Union[str, Pattern[str]], default=None, replace_entiti
return result
return default

# For easy copy-paste from Scrapy/parsel code when needed :)
def get(self, default=None):
"""Returns the first item of the current list
:param default: the default value to return if the current list is empty
"""
return self[0] if len(self) > 0 else default

def extract(self):
return self

extract_first = get
get_all = extract


class AttributesHandler(Mapping):
"""A read-only mapping to use instead of the standard dictionary for the speed boost but at the same time I use it to add more functionalities.
Expand Down
17 changes: 17 additions & 0 deletions scrapling/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,16 @@ def previous(self) -> Union['Adaptor', None]:

return self.__convert_results(prev_element)

# For easy copy-paste from Scrapy/parsel code when needed :)
def get(self, default=None):
return self

def get_all(self):
return self

extract = get_all
extract_first = get

def __str__(self) -> str:
return self.html_content

Expand Down Expand Up @@ -1073,12 +1083,19 @@ def filter(self, func: Callable[['Adaptor'], bool]) -> Union['Adaptors', List]:
]
return self.__class__(results) if results else results

# For easy copy-paste from Scrapy/parsel code when needed :)
def get(self, default=None):
"""Returns the first item of the current list
:param default: the default value to return if the current list is empty
"""
return self[0] if len(self) > 0 else default

def extract(self):
return self

extract_first = get
get_all = extract

@property
def first(self):
"""Returns the first item of the current list or `None` if the list is empty"""
Expand Down

0 comments on commit 45e86f5

Please sign in to comment.