Skip to main content
The Selector class is the core component of Scrapling that wraps HTML content and provides powerful methods for selecting and extracting data using CSS, XPath, or text-based queries.

Constructor

str | bytes
required
HTML content as either string or bytes
str
default:""
Store a URL with the HTML data for retrieving later
str
default:"utf-8"
The encoding type used in HTML parsing
bool
default:"true"
Should always be enabled when parsing large HTML documents. Controls the libxml2 feature that forbids parsing certain large documents to protect from possible memory exhaustion
HtmlElement
default:"None"
Used internally to pass etree objects. Don’t use unless you know what you’re doing
bool
default:"false"
Whether to drop comments while parsing the HTML body
bool
default:"false"
Whether to drop CDATA while parsing the HTML body
bool
default:"false"
Globally turn off the adaptive feature in all functions. Takes higher priority over all adaptive related arguments/functions in the class
Any
default:"SQLiteStorageSystem"
The storage class to be passed for adaptive functionalities
Dict
default:"None"
A dictionary of argument-value pairs to be passed for the storage class. If empty, default values will be used

Properties

tag

Get the tag name of the element. Returns: The element’s tag name as a string, or "#text" for text nodes

text

Get text content of the element. Returns: A TextHandler object containing the element’s text

attrib

Get attributes of the element. Returns: An AttributesHandler object containing the element’s attributes

html_content

Return the inner HTML code of the element. Returns: A TextHandler containing the element’s inner HTML

body

Return the raw body of the current Selector without any processing. Useful for binary and non-HTML requests. Returns: The raw body content

parent

Return the direct parent of the element. Returns: The parent Selector or None if there is no parent

children

Return the children elements of the current element. Returns: A Selectors object containing child elements, or empty list if none

siblings

Return other children of the current element’s parent. Returns: A Selectors object containing sibling elements, or empty list if none

below_elements

Return all elements under the current element in the DOM tree. Returns: A Selectors object containing all descendant elements

path

Returns a list of type Selectors that contains the path leading to the current element from the root. Returns: A Selectors object representing the element’s path

next

Returns the next element of the current element in the children of the parent. Returns: The next Selector or None if there isn’t one

previous

Returns the previous element of the current element in the children of the parent. Returns: The previous Selector or None if there isn’t one

Selection Methods

css()

Search the current tree with CSS3 selectors.
str
required
The CSS3 selector to be used
str
default:""
A string that will be used to save/retrieve element’s data in adaptive, otherwise the selector will be used. Recommended if you plan to use a different selector later and want to relocate the same element(s)
bool
default:"false"
Enabled will make the function try to relocate the element if it was saved before
bool
default:"false"
Automatically save new elements for adaptive later
int
default:"0"
The minimum percentage to accept while adaptive is working. Don’t play with this number unless you know what you’re doing
Returns: A Selectors object

xpath()

Search the current tree with XPath selectors.
str
required
The XPath selector to be used
str
default:""
A string that will be used to save/retrieve element’s data in adaptive, otherwise the selector will be used. Recommended if you plan to use a different selector later and want to relocate the same element(s)
bool
default:"false"
Enabled will make the function try to relocate the element if it was saved before
bool
default:"false"
Automatically save new elements for adaptive later
int
default:"0"
The minimum percentage to accept while adaptive is working. Don’t play with this number unless you know what you’re doing
Any
Additional keyword arguments will be passed as XPath variables in the XPath expression
Returns: A Selectors object

find_all()

Find elements by filters of your creation.
str | Iterable[str] | Pattern | Callable | Dict[str, str]
Tag name(s), iterable of tag names, regex patterns, function, or a dictionary of elements’ attributes. Leave empty for selecting all
str
The attributes you want to filter elements based on
Returns: A Selectors object of the elements or empty list

find()

Find elements by filters of your creation, then return the first result.
str | Iterable[str] | Pattern | Callable | Dict[str, str]
Tag name(s), iterable of tag names, regex patterns, function, or a dictionary of elements’ attributes. Leave empty for selecting all
str
The attributes you want to filter elements based on
Returns: The first Selector object or None if the result didn’t match

find_by_text()

Find elements that have text content fully/partially matching the input.
str
required
Text query to match
bool
default:"true"
Returns the first element that matches conditions
bool
default:"false"
If enabled, the function returns elements that contain the input text
bool
default:"false"
If enabled, the letters case will be taken into consideration
bool
default:"true"
If enabled, this will ignore all whitespaces and consecutive spaces while matching
Returns: A Selector if first_match=True, otherwise Selectors

find_by_regex()

Find elements whose text content matches the input regex pattern.
str | Pattern[str]
required
Regex query/pattern to match
bool
default:"true"
Return the first element that matches conditions
bool
default:"false"
If enabled, the letters case will be taken into consideration in the regex
bool
default:"true"
If enabled, this will ignore all whitespaces and consecutive spaces while matching
Returns: A Selector if first_match=True, otherwise Selectors

find_similar()

Find elements that are in the same tree depth with the same tag name and match the current element attributes with a percentage higher than the threshold.
float
default:"0.2"
The percentage to use while comparing element attributes. Don’t play with this number unless you’re getting unwanted results
List | Tuple
default:"('href', 'src')"
Attribute names to ignore while matching attributes. Default ignores href and src as URLs can change between elements
bool
default:"false"
If True, element text content will be taken into calculation while matching. Not recommended in normal cases
Returns: A Selectors container of Selector objects or empty list

Extraction Methods

get_all_text()

Get all child strings of this element, concatenated using the given separator.
str
default:"\\n"
Strings will be concatenated using this separator
bool
default:"false"
If True, strings will be stripped before being concatenated
Tuple
default:"('script', 'style')"
A tuple of all tag names you want to ignore
bool
default:"true"
If enabled, elements with text-content that is empty or only whitespaces will be ignored
Returns: A TextHandler object

get()

Serialize this element to a string. For text nodes, returns the text value. For HTML elements, returns the outer HTML. Returns: A TextHandler containing the serialized string

getall()

Return a single-element list containing this element’s serialized string. Returns: A TextHandlers list with one element

json()

Return JSON response if the response is jsonable. Returns: A dictionary parsed from JSON Raises: Exception if content is not valid JSON

re()

Apply the given regex to the current text and return a list of strings with the matches.
str | Pattern[str]
required
Can be either a compiled regular expression or a string
bool
default:"true"
If enabled, character entity references are replaced by their corresponding character
bool
default:"false"
If enabled, this will ignore all whitespaces and consecutive spaces while matching
bool
default:"true"
If disabled, the function will set the regex to ignore the letters case while compiling it
Returns: A TextHandlers list of matches

re_first()

Apply the given regex to text and return the first match if found, otherwise return the default value.
str | Pattern[str]
required
Can be either a compiled regular expression or a string
Any
default:"None"
The default value to be returned if there is no match
bool
default:"true"
If enabled, character entity references are replaced by their corresponding character
bool
default:"false"
If enabled, this will ignore all whitespaces and consecutive spaces while matching
bool
default:"true"
If disabled, the function will set the regex to ignore the letters case while compiling it
Returns: A TextHandler with the first match or the default value

Utility Methods

prettify()

Return a prettified version of the element’s inner HTML code. Returns: A TextHandler with formatted HTML

has_class()

Check if the element has a specific class.
str
required
The class name to check for
Returns: True if element has class with that name, otherwise False

urljoin()

Join this Selector’s url with a relative url to form an absolute full URL.
str
required
The relative URL to join
Returns: The absolute URL as a string

iterancestors()

Return a generator that loops over all ancestors of the element, starting with the element’s parent. Returns: A generator yielding Selector objects

find_ancestor()

Loop over all ancestors of the element until one matches the passed function.
Callable[[Selector], bool]
required
A function that takes each ancestor as an argument and returns True/False
Returns: The first ancestor that matches the function or None otherwise

Adaptive Methods

save()

Saves the element’s unique properties to the storage for retrieval and relocation later.
HtmlElement
required
The element itself to save to storage. Can be a Selector or pure HtmlElement
str
required
The identifier that will be used to retrieve the element later from the storage

retrieve()

Using the identifier, search the storage and return the unique properties of the element.
str
required
The identifier used to retrieve the element from the storage
Returns: A dictionary of the unique properties or None

relocate()

Search again for the element in the page tree, used automatically on page structure change.
Union[Dict, HtmlElement, Selector]
required
The element to relocate in the tree
int
default:"0"
The minimum percentage to accept. Don’t play with this number unless you know what you’re doing
bool
default:"false"
If True, the return result will be converted to Selectors object
Returns: List of pure HTML elements that got the highest matching score or Selectors object

Magic Methods

__getitem__()

Get element attribute by key. Example:

__contains__()

Check if element has an attribute. Example:

Aliases

For compatibility with Scrapy/Parsel:
  • extract() - alias for getall()
  • extract_first() - alias for get()