同步完整源码 - 2026-05-24

This commit is contained in:
xiaoxue
2026-05-24 23:23:00 +08:00
commit a747529fef
238 changed files with 43516 additions and 0 deletions
View File
+111
View File
@@ -0,0 +1,111 @@
import asyncio
import pytest
from scrapling import Selector
class TestParserAdaptive:
def test_element_relocation(self):
"""Test relocating element after structure change"""
original_html = """
<div class="container">
<section class="products">
<article class="product" id="p1">
<h3>Product 1</h3>
<p class="description">Description 1</p>
</article>
<article class="product" id="p2">
<h3>Product 2</h3>
<p class="description">Description 2</p>
</article>
</section>
</div>
"""
changed_html = """
<div class="new-container">
<div class="product-wrapper">
<section class="products">
<article class="product new-class" data-id="p1">
<div class="product-info">
<h3>Product 1</h3>
<p class="new-description">Description 1</p>
</div>
</article>
<article class="product new-class" data-id="p2">
<div class="product-info">
<h3>Product 2</h3>
<p class="new-description">Description 2</p>
</div>
</article>
</section>
</div>
</div>
"""
old_page = Selector(original_html, url="example.com", adaptive=True)
new_page = Selector(changed_html, url="example.com", adaptive=True)
# 'p1' was used as ID and now it's not and all the path elements have changes
# Also at the same time testing `adaptive` vs combined selectors
_ = old_page.css("#p1, #p2", auto_save=True)[0]
relocated = new_page.css("#p1", adaptive=True)
assert relocated is not None
assert relocated[0].attrib["data-id"] == "p1"
assert relocated[0].has_class("new-class")
assert relocated[0].css(".new-description")[0].text == "Description 1"
@pytest.mark.asyncio
async def test_element_relocation_async(self):
"""Test relocating element after structure change in async mode"""
original_html = """
<div class="container">
<section class="products">
<article class="product" id="p1">
<h3>Product 1</h3>
<p class="description">Description 1</p>
</article>
<article class="product" id="p2">
<h3>Product 2</h3>
<p class="description">Description 2</p>
</article>
</section>
</div>
"""
changed_html = """
<div class="new-container">
<div class="product-wrapper">
<section class="products">
<article class="product new-class" data-id="p1">
<div class="product-info">
<h3>Product 1</h3>
<p class="new-description">Description 1</p>
</div>
</article>
<article class="product new-class" data-id="p2">
<div class="product-info">
<h3>Product 2</h3>
<p class="new-description">Description 2</p>
</div>
</article>
</section>
</div>
</div>
"""
# Simulate async operation
await asyncio.sleep(0.1) # Minimal async operation
old_page = Selector(original_html, url="example.com", adaptive=True)
new_page = Selector(changed_html, url="example.com", adaptive=True)
# 'p1' was used as ID and now it's not and all the path elements have changes
# Also at the same time testing `adaptive` vs combined selectors
_ = old_page.css("#p1, #p2", auto_save=True)[0]
relocated = new_page.css("#p1", adaptive=True)
assert relocated is not None
assert relocated[0].attrib["data-id"] == "p1"
assert relocated[0].has_class("new-class")
assert relocated[0].css(".new-description")[0].text == "Description 1"
+66
View File
@@ -0,0 +1,66 @@
"""
Tests for Selector.iterancestors() and Selector.find_ancestor() methods.
Target file: tests/parser/test_general.py (append to TestElementNavigation class)
"""
import pytest
from scrapling import Selector
@pytest.fixture
def nested_page():
html = """
<html><body>
<div id="level1">
<section id="level2" class="wrapper">
<article id="level3" class="card">
<p id="level4"><span id="target">deep text</span></p>
</article>
</section>
</div>
</body></html>
"""
return Selector(html, adaptive=False)
class TestAncestorNavigation:
def test_iterancestors_returns_all_ancestors(self, nested_page):
"""iterancestors() should yield every ancestor up to <html>"""
target = nested_page.css("#target")[0]
ancestor_tags = [a.tag for a in target.iterancestors()]
# Expected order: p → article → section → div → body → html
assert ancestor_tags[:4] == ["p", "article", "section", "div"]
assert "body" in ancestor_tags
assert "html" in ancestor_tags
def test_iterancestors_order_is_bottom_up(self, nested_page):
"""iterancestors() should start from the immediate parent, not the root"""
target = nested_page.css("#target")[0]
first_ancestor = next(target.iterancestors())
assert first_ancestor.attrib.get("id") == "level4"
def test_find_ancestor_returns_first_match(self, nested_page):
"""find_ancestor() should return the closest ancestor matching the predicate"""
target = nested_page.css("#target")[0]
# Looking for the nearest ancestor with class "card"
result = target.find_ancestor(lambda el: el.has_class("card"))
assert result is not None
assert result.attrib.get("id") == "level3"
def test_find_ancestor_returns_none_when_not_found(self, nested_page):
"""find_ancestor() should return None if no ancestor matches"""
target = nested_page.css("#target")[0]
result = target.find_ancestor(lambda el: el.has_class("nonexistent-class"))
assert result is None
def test_iterancestors_on_text_node_is_empty(self, nested_page):
"""iterancestors() on a text node should yield nothing (not raise)"""
text_node = nested_page.css("#target::text")[0]
ancestors = list(text_node.iterancestors())
assert ancestors == []
def test_find_ancestor_on_root_element_returns_none(self, nested_page):
"""find_ancestor() on the root <html> element should return None gracefully"""
# html element has no ancestors
html_el = nested_page.css("html")[0]
result = html_el.find_ancestor(lambda el: True)
assert result is None
+336
View File
@@ -0,0 +1,336 @@
import pytest
import json
from scrapling import Selector
from scrapling.core.custom_types import AttributesHandler
class TestAttributesHandler:
"""Test AttributesHandler functionality"""
@pytest.fixture
def sample_html(self):
return """
<html>
<body>
<div id="main"
class="container active"
data-config='{"theme": "dark", "version": 2.5}'
data-items='[1, 2, 3, 4, 5]'
data-invalid-json='{"broken: json}'
title="Main Container"
style="color: red; background: blue;"
data-empty=""
data-number="42"
data-bool="true"
data-url="https://example.com/page?param=value"
custom-attr="custom-value"
data-nested='{"user": {"name": "John", "age": 30}}'
data-encoded="&lt;div&gt;HTML&lt;/div&gt;"
onclick="handleClick()"
data-null="null"
data-undefined="undefined">
Content
</div>
<input type="text"
name="username"
value="test@example.com"
placeholder="Enter email"
required
disabled>
<img src="/images/photo.jpg"
alt="Photo"
width="100"
height="100"
loading="lazy">
</body>
</html>
"""
@pytest.fixture
def attributes(self, sample_html):
page = Selector(sample_html)
element = page.css("#main")[0]
return element.attrib
def test_basic_attribute_access(self, attributes):
"""Test basic attribute access"""
# Dict-like access
assert attributes["id"] == "main"
assert attributes["class"] == "container active"
assert attributes["title"] == "Main Container"
# Key existence
assert "id" in attributes
assert "nonexistent" not in attributes
# Get with default
assert attributes.get("id") == "main"
assert attributes.get("nonexistent") is None
assert attributes.get("nonexistent", "default") == "default"
def test_iteration_methods(self, attributes):
"""Test iteration over attributes"""
# Keys
keys = list(attributes.keys())
assert "id" in keys
assert "class" in keys
assert "data-config" in keys
# Values
values = list(attributes.values())
assert "main" in values
assert "container active" in values
# Items
items = dict(attributes.items())
assert items["id"] == "main"
assert items["class"] == "container active"
# Length
assert len(attributes) > 0
def test_json_parsing(self, attributes):
"""Test JSON parsing from attributes"""
# Valid JSON object
config = attributes["data-config"].json()
assert config["theme"] == "dark"
assert config["version"] == 2.5
# Valid JSON array
items = attributes["data-items"].json()
assert items == [1, 2, 3, 4, 5]
# Nested JSON
nested = attributes["data-nested"].json()
assert nested["user"]["name"] == "John"
assert nested["user"]["age"] == 30
# JSON null
assert attributes["data-null"].json() is None
def test_json_error_handling(self, attributes):
"""Test JSON parsing error handling"""
# Invalid JSON should raise error or return None
with pytest.raises((json.JSONDecodeError, AttributeError)):
attributes["data-invalid-json"].json()
# Non-existent attribute
with pytest.raises(KeyError):
attributes["nonexistent"].json()
def test_json_string_property(self, attributes):
"""Test json_string property"""
# Should return JSON representation of all attributes
json_string = attributes.json_string
assert isinstance(json_string, bytes)
# Parse it back
parsed = json.loads(json_string)
assert parsed["id"] == "main"
assert parsed["class"] == "container active"
def test_search_values(self, attributes):
"""Test search_values method"""
# Exact match
results = list(attributes.search_values("main", partial=False))
assert len(results) == 1
assert "id" in results[0]
# Partial match
results = list(attributes.search_values("container", partial=True))
assert len(results) >= 1
found_keys = []
for result in results:
found_keys.extend(result.keys())
assert "class" in found_keys or "title" in found_keys
# Case sensitivity
results = list(attributes.search_values("MAIN", partial=False))
assert len(results) == 0 # Should be case-sensitive by default
# Multiple matches
results = list(attributes.search_values("2", partial=True))
assert len(results) > 1 # Should find multiple attributes
# No matches
results = list(attributes.search_values("nonexistent", partial=False))
assert len(results) == 0
def test_special_attribute_types(self, sample_html):
"""Test handling of special attribute types"""
page = Selector(sample_html)
# Boolean attributes
input_elem = page.css("input")[0]
assert "required" in input_elem.attrib
assert "disabled" in input_elem.attrib
# Empty attributes
main_elem = page.css("#main")[0]
assert main_elem.attrib["data-empty"] == ""
# Numeric string attributes
assert main_elem.attrib["data-number"] == "42"
assert main_elem.attrib["data-bool"] == "true"
def test_attribute_modification(self, sample_html):
"""Test that AttributesHandler is read-only (if applicable)"""
page = Selector(sample_html)
element = page.css("#main")[0]
attrs = element.attrib
# Test if attributes can be modified
# This behavior depends on implementation
original_id = attrs["id"]
try:
attrs["id"] = "new-id"
# If modification is allowed
assert attrs["id"] == "new-id"
# Reset
attrs["id"] = original_id
except (TypeError, AttributeError):
# If modification is not allowed (read-only)
assert attrs["id"] == original_id
def test_string_representation(self, attributes):
"""Test string representations"""
# __str__
str_repr = str(attributes)
assert isinstance(str_repr, str)
assert "id" in str_repr or "main" in str_repr
# __repr__
repr_str = repr(attributes)
assert isinstance(repr_str, str)
def test_edge_cases(self, sample_html):
"""Test edge cases and special scenarios"""
page = Selector(sample_html)
# Element with no attributes
page_with_no_attrs = Selector("<div>Content</div>")
elem = page_with_no_attrs.css("div")[0]
assert len(elem.attrib) == 0
assert list(elem.attrib.keys()) == []
assert elem.attrib.get("any") is None
# Element with encoded content
main_elem = page.css("#main")[0]
encoded = main_elem.attrib["data-encoded"]
assert "<" in encoded # Should decode it
# Style attribute parsing
style = main_elem.attrib["style"]
assert "color: red" in style
assert "background: blue" in style
def test_url_attribute(self, attributes):
"""Test URL attributes"""
url = attributes["data-url"]
assert url == "https://example.com/page?param=value"
# Could test URL joining if AttributesHandler supports it
# based on the parent element's base URL
def test_comparison_operations(self, sample_html):
"""Test comparison operations if supported"""
page = Selector(sample_html)
elem1 = page.css("#main")[0]
elem2 = page.css("input")[0]
# Different elements should have different attributes
assert elem1.attrib != elem2.attrib
# The same element should have equal attributes
elem1_again = page.css("#main")[0]
assert elem1.attrib == elem1_again.attrib
def test_complex_search_patterns(self, attributes):
"""Test complex search patterns"""
# Search for JSON-containing attributes
json_attrs = []
for key, value in attributes.items():
try:
if isinstance(value, str) and (value.startswith('{') or value.startswith('[')):
json.loads(value)
json_attrs.append(key)
except:
pass
assert "data-config" in json_attrs
assert "data-items" in json_attrs
assert "data-nested" in json_attrs
def test_attribute_filtering(self, attributes):
"""Test filtering attributes by patterns"""
# Get all data-* attributes
data_attrs = {k: v for k, v in attributes.items() if k.startswith("data-")}
assert len(data_attrs) > 5
assert "data-config" in data_attrs
assert "data-items" in data_attrs
# Get all event handler attributes
event_attrs = {k: v for k, v in attributes.items() if k.startswith("on")}
assert "onclick" in event_attrs
def test_performance_with_many_attributes(self):
"""Test performance with elements having many attributes"""
# Create an element with many attributes
attrs_list = [f'data-attr{i}="value{i}"' for i in range(100)]
html = f'<div id="test" {" ".join(attrs_list)}>Content</div>'
page = Selector(html)
element = page.css("#test")[0]
attribs = element.attrib
# Should handle many attributes efficiently
assert len(attribs) == 101 # id + 100 data attributes
# Search should still work efficiently
results = list(attribs.search_values("value50", partial=False))
assert len(results) == 1
def test_unicode_attributes(self):
"""Test handling of Unicode in attributes"""
html = """
<div id="unicode-test"
data-emoji="😀🎉"
data-chinese="你好世界"
data-arabic="مرحبا بالعالم"
data-special="café naïve">
</div>
"""
page = Selector(html)
attrs = page.css("#unicode-test")[0].attrib
assert attrs["data-emoji"] == "😀🎉"
assert attrs["data-chinese"] == "你好世界"
assert attrs["data-arabic"] == "مرحبا بالعالم"
assert attrs["data-special"] == "café naïve"
# Search with Unicode
results = list(attrs.search_values("你好", partial=True))
assert len(results) == 1
def test_malformed_attributes(self):
"""Test handling of malformed attributes"""
# Various malformed HTML scenarios
test_cases = [
'<div id="test" class=>Content</div>', # Empty attribute value
'<div id="test" class>Content</div>', # No attribute value
'<div id="test" data-"invalid"="value">Content</div>', # Invalid attribute name
'<div id=test class=no-quotes>Content</div>', # Unquoted values
]
for html in test_cases:
try:
page = Selector(html)
if page.css("div"):
attrs = page.css("div")[0].attrib
# Should handle gracefully without crashing
assert isinstance(attrs, AttributesHandler)
except:
# Some malformed HTML might not parse at all
pass
@@ -0,0 +1,78 @@
"""
Tests for Selector.find_similar() with non-default parameters.
Target file: tests/parser/test_general.py (append to TestSimilarElements class)
"""
import pytest
from scrapling import Selector
@pytest.fixture
def product_page():
html = """
<html><body>
<div class="product-list">
<div class="product" data-category="fruit" data-price="10">
<span class="name">Apple</span>
</div>
<div class="product" data-category="fruit" data-price="5">
<span class="name">Banana</span>
</div>
<div class="product" data-category="veggie" data-price="3">
<span class="name">Carrot</span>
</div>
<!-- Structurally similar but different tag - should NOT be found -->
<section class="product" data-category="fruit" data-price="8">
<span class="name">Grape</span>
</section>
</div>
</body></html>
"""
return Selector(html, adaptive=False)
class TestFindSimilarAdvanced:
def test_find_similar_default_finds_same_tag_siblings(self, product_page):
"""find_similar() with defaults should find div.product siblings, not the section"""
first = product_page.css("div.product")[0]
similar = first.find_similar()
tags = [el.tag for el in similar]
assert all(t == "div" for t in tags), "Should only return <div> elements"
assert len(similar) == 2 # Banana and Carrot, not Grape (section)
def test_find_similar_high_threshold_filters_more(self, product_page):
"""A higher similarity_threshold should return fewer (or equal) results"""
first = product_page.css("div.product")[0]
low_threshold = first.find_similar(similarity_threshold=0.1)
high_threshold = first.find_similar(similarity_threshold=0.9)
assert len(high_threshold) <= len(low_threshold)
def test_find_similar_match_text_excludes_different_text(self, product_page):
"""match_text=True should factor in text content during similarity scoring"""
first = product_page.css("div.product")[0] # Apple
# With match_text=True and a high threshold, "Apple" vs "Banana"/"Carrot" text
# should reduce similarity scores - result count may drop
with_text = first.find_similar(similarity_threshold=0.8, match_text=True)
without_text = first.find_similar(similarity_threshold=0.8, match_text=False)
# match_text=True is stricter when text differs, so result should be <= without_text
assert len(with_text) <= len(without_text)
def test_find_similar_ignore_attributes_affects_matching(self, product_page):
"""Ignoring data-price should make more elements qualify as similar"""
first = product_page.css("div.product")[0]
# Ignore both data-price and data-category → only class matters → all 3 divs match
ignore_all_data = first.find_similar(
similarity_threshold=0.2,
ignore_attributes=["data-price", "data-category"]
)
# Ignore nothing → data-category difference (fruit vs veggie) may reduce matches
ignore_nothing = first.find_similar(
similarity_threshold=0.9,
ignore_attributes=[]
)
assert len(ignore_all_data) >= len(ignore_nothing)
def test_find_similar_on_text_node_returns_empty(self, product_page):
"""find_similar() on a text node should return empty Selectors without raising"""
text_node = product_page.css(".name::text")[0]
result = text_node.find_similar()
assert len(result) == 0
+380
View File
@@ -0,0 +1,380 @@
import pickle
import time
import logging
import pytest
from cssselect import SelectorError, SelectorSyntaxError
from scrapling import Selector
logging.getLogger("scrapling").setLevel(logging.DEBUG)
@pytest.fixture
def html_content():
return """
<html>
<head>
<title>Complex Web Page</title>
<style>
.hidden { display: none; }
</style>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
<section id="products" schema='{"jsonable": "data"}'>
<h2>Products</h2>
<div class="product-list">
<article class="product" data-id="1">
<h3>Product 1</h3>
<p class="description">This is product 1</p>
<span class="price">$10.99</span>
<div class="hidden stock">In stock: 5</div>
</article>
<article class="product" data-id="2">
<h3>Product 2</h3>
<p class="description">This is product 2</p>
<span class="price">$20.99</span>
<div class="hidden stock">In stock: 3</div>
</article>
<article class="product" data-id="3">
<h3>Product 3</h3>
<p class="description">This is product 3</p>
<span class="price">$15.99</span>
<div class="hidden stock">Out of stock</div>
</article>
</div>
</section>
<section id="reviews">
<h2>Customer Reviews</h2>
<div class="review-list">
<div class="review" data-rating="5">
<p class="review-text">Great product!</p>
<span class="reviewer">John Doe</span>
</div>
<div class="review" data-rating="4">
<p class="review-text">Good value for money.</p>
<span class="reviewer">Jane Smith</span>
</div>
</div>
</section>
</main>
<footer>
<p>&copy; 2024 Our Company</p>
</footer>
<script id="page-data" type="application/json">
{"lastUpdated": "2024-09-22T10:30:00Z", "totalProducts": 3}
</script>
</body>
</html>
"""
@pytest.fixture
def page(html_content):
return Selector(html_content, adaptive=False)
# CSS Selector Tests
class TestCSSSelectors:
def test_basic_product_selection(self, page):
"""Test selecting all product elements"""
elements = page.css("main #products .product-list article.product")
assert len(elements) == 3
def test_in_stock_product_selection(self, page):
"""Test selecting in-stock products"""
in_stock_products = page.css(
'main #products .product-list article.product:not(:contains("Out of stock"))'
)
assert len(in_stock_products) == 2
# XPath Selector Tests
class TestXPathSelectors:
def test_high_rating_reviews(self, page):
"""Test selecting reviews with high ratings"""
reviews = page.xpath(
'//section[@id="reviews"]//div[contains(@class, "review") and @data-rating >= 4]'
)
assert len(reviews) == 2
def test_high_priced_products(self, page):
"""Test selecting products above a certain price"""
high_priced_products = page.xpath(
'//article[contains(@class, "product")]'
'[number(translate(substring-after(.//span[@class="price"], "$"), ",", "")) > 15]'
)
assert len(high_priced_products) == 2
# Text Matching Tests
class TestTextMatching:
def test_regex_multiple_matches(self, page):
"""Test finding multiple matches with regex"""
stock_info = page.find_by_regex(r"In stock: \d+", first_match=False)
assert len(stock_info) == 2
def test_regex_first_match(self, page):
"""Test finding the first match with regex"""
stock_info = page.find_by_regex(
r"In stock: \d+", first_match=True, case_sensitive=True
)
assert stock_info.text == "In stock: 5"
def test_partial_text_match(self, page):
"""Test finding elements with partial text match"""
stock_info = page.find_by_text(r"In stock:", partial=True, first_match=False)
assert len(stock_info) == 2
def test_exact_text_match(self, page):
"""Test finding elements with exact text match"""
out_of_stock = page.find_by_text(
"Out of stock", partial=False, first_match=False
)
assert len(out_of_stock) == 1
# Similar Elements Tests
class TestSimilarElements:
def test_finding_similar_products(self, page):
"""Test finding similar product elements"""
first_product = page.css(".product").first
similar_products = first_product.find_similar()
assert len(similar_products) == 2
def test_finding_similar_reviews(self, page):
"""Test finding similar review elements with additional filtering"""
first_review = page.find("div", class_="review")
similar_high_rated_reviews = [
review
for review in first_review.find_similar()
if int(review.attrib.get("data-rating", 0)) >= 4
]
assert len(similar_high_rated_reviews) == 1
# Error Handling Tests
class TestErrorHandling:
def test_invalid_selector_initialization(self):
"""Test various invalid Selector initializations"""
# No arguments
with pytest.raises(ValueError):
_ = Selector(adaptive=False)
with pytest.raises(TypeError):
_ = Selector(content=1, adaptive=False)
def test_invalid_storage(self, page, html_content):
"""Test invalid storage parameter"""
with pytest.raises(ValueError):
_ = Selector(html_content, storage=object, adaptive=True)
def test_bad_selectors(self, page):
"""Test handling of invalid selectors"""
with pytest.raises((SelectorError, SelectorSyntaxError)):
page.css("4 ayo")
with pytest.raises((SelectorError, SelectorSyntaxError)):
page.xpath("4 ayo")
# Pickling and Object Representation Tests
class TestPicklingAndRepresentation:
def test_unpickleable_objects(self, page):
"""Test that Selector objects cannot be pickled"""
table = page.css(".product-list")[0]
with pytest.raises(TypeError):
pickle.dumps(table)
def test_string_representations(self, page):
"""Test custom string representations of objects"""
table = page.css(".product-list")[0]
assert issubclass(type(table.__str__()), str)
assert issubclass(type(table.__repr__()), str)
assert issubclass(type(table.attrib.__str__()), str)
assert issubclass(type(table.attrib.__repr__()), str)
# Navigation and Traversal Tests
class TestElementNavigation:
def test_basic_navigation_properties(self, page):
"""Test basic navigation properties of elements"""
table = page.css(".product-list")[0]
assert table.path is not None
assert table.html_content != ""
assert table.prettify() != ""
def test_parent_and_sibling_navigation(self, page):
"""Test parent and sibling navigation"""
table = page.css(".product-list")[0]
parent = table.parent
assert parent["id"] == "products"
parent_siblings = parent.siblings
assert len(parent_siblings) == 1
def test_child_navigation(self, page):
"""Test child navigation"""
table = page.css(".product-list")[0]
children = table.children
assert len(children) == 3
def test_next_and_previous_navigation(self, page):
"""Test next and previous element navigation"""
child = page.css(".product-list")[0].find({"data-id": "1"})
next_element = child.next
assert next_element.attrib["data-id"] == "2"
prev_element = next_element.previous
assert prev_element.tag == child.tag
def test_ancestor_finding(self, page):
"""Test finding ancestors of elements"""
all_prices = page.css(".price")
products_with_prices = [
price.find_ancestor(lambda p: p.has_class("product"))
for price in all_prices
]
assert len(products_with_prices) == 3
# JSON and Attribute Tests
class TestJSONAndAttributes:
def test_json_conversion(self, page):
"""Test converting content to JSON"""
script_content = page.css("#page-data::text")[0].get()
assert issubclass(type(script_content.sort()), str)
page_data = script_content.json()
assert page_data["totalProducts"] == 3
assert "lastUpdated" in page_data
def test_attribute_operations(self, page):
"""Test various attribute-related operations"""
# Product ID extraction
products = page.css(".product")
product_ids = [product.attrib["data-id"] for product in products]
assert product_ids == ["1", "2", "3"]
assert "data-id" in products[0]
# Review rating calculations
reviews = page.css(".review")
review_ratings = [int(review.attrib["data-rating"]) for review in reviews]
assert sum(review_ratings) / len(review_ratings) == 4.5
# Attribute searching
key_value = list(products[0].attrib.search_values("1", partial=False))
assert list(key_value[0].keys()) == ["data-id"]
key_value = list(products[0].attrib.search_values("1", partial=True))
assert list(key_value[0].keys()) == ["data-id"]
# JSON attribute conversion
attr_json = page.css("#products").first.attrib["schema"].json()
assert attr_json == {"jsonable": "data"}
assert isinstance(page.css("#products")[0].attrib.json_string, bytes)
# Performance Test
def test_large_html_parsing_performance():
"""Test parsing and selecting performance on large HTML"""
large_html = (
"<html><body>"
+ '<div class="item">' * 5000
+ "</div>" * 5000
+ "</body></html>"
)
start_time = time.time()
parsed = Selector(large_html, adaptive=False)
elements = parsed.css(".item")
end_time = time.time()
# assert len(elements) == 5000 # GitHub actions don't like this line
# Converting 5000 elements to a class and doing operations on them will take time
# Based on my tests with 100 runs, 1 loop each Scrapling (given the extra work/features) takes 10.4ms on average
assert (
end_time - start_time < 0.5
) # Locally I test on 0.1 but on GitHub actions with browsers and threading sometimes closing adds fractions of seconds
# Selector Generation Test
def test_selectors_generation(page):
"""Try to create selectors for all elements in the page"""
def _traverse(element: Selector):
assert isinstance(element.generate_css_selector, str)
assert isinstance(element.generate_full_css_selector, str)
assert isinstance(element.generate_xpath_selector, str)
assert isinstance(element.generate_full_xpath_selector, str)
for branch in element.children:
_traverse(branch)
_traverse(page)
def test_full_path_selector_no_duplicate_ids():
"""Test that full path selectors don't duplicate id segments (regression test)"""
html = '<html><body><div id="main"><p id="target">Hello</p></div></body></html>'
page = Selector(html)
target = page.css("#target").first
# CSS full path should not duplicate id selectors
css_full = target.generate_full_css_selector
assert css_full.count("#target") == 1, f"Duplicate #target in CSS full path: {css_full}"
assert css_full.count("#main") == 1, f"Duplicate #main in CSS full path: {css_full}"
# XPath full path should not duplicate id selectors
xpath_full = target.generate_full_xpath_selector
assert xpath_full.count("@id='target'") == 1, f"Duplicate @id='target' in XPath full path: {xpath_full}"
assert xpath_full.count("@id='main'") == 1, f"Duplicate @id='main' in XPath full path: {xpath_full}"
# The generated CSS selector should actually select the correct element
result = page.css(css_full)
assert len(result) == 1
assert result.first.text == "Hello"
# The generated XPath selector should also select the correct element
result = page.xpath(xpath_full)
assert len(result) == 1, f"XPath '{xpath_full}' selected {len(result)} elements, expected 1"
assert result.first.text == "Hello"
def test_full_path_selector_mixed_id_and_no_id():
"""Test full path selectors with a mix of elements with and without ids"""
html = '<html><body><div id="wrapper"><section><p>Text</p></section></div></body></html>'
page = Selector(html)
target = page.css("p").first
css_full = target.generate_full_css_selector
# p has no id, so it should appear as a tag name; div has id
assert "#wrapper" in css_full
assert css_full.count("#wrapper") == 1
# Verify the selector works
result = page.css(css_full)
assert len(result) == 1
assert result.first.text == "Text"
# Miscellaneous Tests
def test_getting_all_text(page):
"""Test getting all text from the page"""
assert page.get_all_text() != ""
def test_regex_on_text(page):
"""Test regex operations on text"""
element = page.css('[data-id="1"] .price')[0]
match = element.re_first(r"[\.\d]+")
assert match == "10.99"
match = element.text.re(r"(\d+)", replace_entities=False)
assert len(match) == 2
+395
View File
@@ -0,0 +1,395 @@
import re
import pytest
from unittest.mock import Mock
from scrapling import Selector, Selectors
from scrapling.core.custom_types import TextHandler, TextHandlers
from scrapling.core.storage import SQLiteStorageSystem
class TestSelectorAdvancedFeatures:
"""Test advanced Selector features like adaptive matching"""
def test_adaptive_initialization_with_storage(self):
"""Test adaptive initialization with custom storage"""
html = "<html><body><p>Test</p></body></html>"
# Use the actual SQLiteStorageSystem for this test
selector = Selector(
content=html,
adaptive=True,
storage=SQLiteStorageSystem,
storage_args={"storage_file": ":memory:", "url": "https://example.com"}
)
assert selector._Selector__adaptive_enabled is True
assert selector._storage is not None
def test_adaptive_initialization_with_default_storage_args(self):
"""Test adaptive initialization with default storage args"""
html = "<html><body><p>Test</p></body></html>"
url = "https://example.com"
# Test that adaptive mode uses default storage when no explicit args provided
selector = Selector(
content=html,
url=url,
adaptive=True
)
# Should create storage with default args
assert selector._storage is not None
def test_adaptive_with_existing_storage(self):
"""Test adaptive initialization with existing storage object"""
html = "<html><body><p>Test</p></body></html>"
mock_storage = Mock()
selector = Selector(
content=html,
adaptive=True,
_storage=mock_storage
)
assert selector._storage is mock_storage
class TestAdvancedSelectors:
"""Test advanced selector functionality"""
@pytest.fixture
def complex_html(self):
return """
<html>
<body>
<div class="container" data-test='{"key": "value"}'>
<p>First paragraph</p>
<!-- Comment -->
<p>Second paragraph</p>
<![CDATA[Some CDATA content]]>
<div class="nested">
<span id="special">Special content</span>
<span>Regular content</span>
</div>
<table>
<tr><td>Cell 1</td><td>Cell 2</td></tr>
<tr><td>Cell 3</td><td>Cell 4</td></tr>
</table>
</div>
</body>
</html>
"""
def test_comment_and_cdata_handling(self, complex_html):
"""Test handling of comments and CDATA"""
# With comments/CDATA kept
page = Selector(
complex_html,
keep_comments=True,
keep_cdata=True
)
content = page.body
assert "Comment" in content
assert "CDATA" in content
# Without comments/CDATA
page = Selector(
complex_html,
keep_comments=False,
keep_cdata=False
)
content = page.html_content
assert "Comment" not in content
def test_advanced_xpath_variables(self, complex_html):
"""Test XPath with variables"""
page = Selector(complex_html)
# Using XPath variables
cells = page.xpath(
"//td[text()=$cell_text]",
cell_text="Cell 1"
)
assert len(cells) == 1
assert cells[0].text == "Cell 1"
def test_pseudo_elements(self, complex_html):
"""Test CSS pseudo-elements"""
page = Selector(complex_html)
# ::text pseudo-element
texts = page.css("p::text")
assert len(texts) == 2
assert isinstance(texts[0], Selector)
assert isinstance(texts[0].get(), TextHandler)
# ::attr() pseudo-element
attrs = page.css("div::attr(class)")
assert "container" in attrs.getall()
def test_complex_attribute_operations(self, complex_html):
"""Test complex attribute handling"""
page = Selector(complex_html)
container = page.css(".container")[0]
# JSON in attributes
data = container.attrib["data-test"].json()
assert data["key"] == "value"
# Attribute searching
matches = list(container.attrib.search_values("container"))
assert len(matches) == 1
def test_url_joining(self):
"""Test URL joining functionality"""
page = Selector("<html></html>", url="https://example.com/page")
# Relative URL
assert page.urljoin("../other") == "https://example.com/other"
assert page.urljoin("/absolute") == "https://example.com/absolute"
assert page.urljoin("relative") == "https://example.com/relative"
def test_find_operations_edge_cases(self, complex_html):
"""Test edge cases in find operations"""
page = Selector(complex_html)
# Multiple argument types
_ = page.find_all(
"span",
["div"],
{"class": "nested"},
lambda e: e.text != ""
)
# Regex pattern matching
pattern = re.compile(r"Cell \d+")
cells = page.find_all(pattern)
assert len(cells) == 4
def test_text_operations_edge_cases(self, complex_html):
"""Test text operation edge cases"""
page = Selector(complex_html)
# get_all_text with a custom separator
text = page.get_all_text(separator=" | ", strip=True)
assert " | " in text
# Ignore specific tags
text = page.get_all_text(ignore_tags=("table",))
assert "Cell" not in text
# With empty values
text = page.get_all_text(valid_values=False)
assert text != ""
def test_get_all_text_preserves_interleaved_text_nodes(self):
"""Test get_all_text preserves interleaved text nodes"""
html = """
<html>
<body>
<main>
string1
<b>string2</b>
string3
<div>
<span>string4</span>
</div>
string5
<script>ignored</script>
string6
<style>ignored</style>
string7
</main>
</body>
</html>
"""
page = Selector(html, adaptive=False)
node = page.css("main")[0]
assert node.get_all_text("\n", strip=True) == "string1\nstring2\nstring3\nstring4\nstring5\nstring6\nstring7"
class TestTextHandlerAdvanced:
"""Test advanced TextHandler functionality"""
def test_text_handler_operations(self):
"""Test various TextHandler operations"""
text = TextHandler(" Hello World ")
# All string methods should return TextHandler
assert isinstance(text.strip(), TextHandler)
assert isinstance(text.upper(), TextHandler)
assert isinstance(text.lower(), TextHandler)
assert isinstance(text.replace("World", "Python"), TextHandler)
# Custom methods
assert text.clean() == "Hello World"
# Sorting
text2 = TextHandler("dcba")
assert text2.sort() == "abcd"
def test_text_handler_regex(self):
"""Test regex operations on TextHandler"""
text = TextHandler("Price: $10.99, Sale: $8.99")
# Basic regex
prices = text.re(r"\$[\d.]+")
assert len(prices) == 2
assert prices[0] == "$10.99"
# Case insensitive
text2 = TextHandler("HELLO hello HeLLo")
matches = text2.re(r"hello", case_sensitive=False)
assert len(matches) == 3
# Clean match
text3 = TextHandler(" He l lo ")
matches = text3.re(r"He l lo", clean_match=True, case_sensitive=False)
assert len(matches) == 1
def test_text_handler_regex_check_match(self):
"""Test TextHandler.re() with check_match=True returns bool"""
text = TextHandler("Price: $10.99")
assert text.re(r"\$[\d.]+", check_match=True) is True
assert text.re(r"no-match-pattern", check_match=True) is False
def test_text_handler_regex_replace_entities_false(self):
"""Test TextHandler.re() with replace_entities=False preserves entities"""
text = TextHandler("Hello &amp; World")
results = text.re(r"&amp;", replace_entities=False)
assert len(results) == 1
assert results[0] == "&amp;"
def test_text_handler_regex_with_groups(self):
"""Test TextHandler.re() with capture groups flattens results"""
text = TextHandler("name=Alice age=30 name=Bob age=25")
results = text.re(r"name=(\w+) age=(\d+)")
assert len(results) == 4
assert "Alice" in results
assert "30" in results
def test_text_handler_re_first_with_default(self):
"""Test TextHandler.re_first() returns default when no match"""
text = TextHandler("no numbers here")
result = text.re_first(r"\d+", default="N/A")
assert result == "N/A"
def test_text_handler_re_first_returns_first_match(self):
"""Test TextHandler.re_first() returns first match"""
text = TextHandler("a1 b2 c3")
result = text.re_first(r"\d")
assert result == "1"
assert isinstance(result, TextHandler)
def test_text_handler_clean_with_entities(self):
"""Test TextHandler.clean() with remove_entities=True"""
text = TextHandler("Hello\t&amp;\nWorld")
cleaned = text.clean(remove_entities=True)
assert "&amp;" not in cleaned
assert "&" in cleaned
assert "\t" not in cleaned
assert "\n" not in cleaned
def test_text_handler_clean_without_entities(self):
"""Test TextHandler.clean() preserves entities by default"""
text = TextHandler("Hello\t&amp;\nWorld")
cleaned = text.clean(remove_entities=False)
assert "&amp;" in cleaned
def test_text_handler_json_valid(self):
"""Test TextHandler.json() with valid JSON"""
text = TextHandler('{"key": "value", "num": 42}')
data = text.json()
assert data["key"] == "value"
assert data["num"] == 42
def test_text_handler_json_invalid(self):
"""Test TextHandler.json() raises on invalid JSON"""
text = TextHandler("not json")
with pytest.raises(Exception):
text.json()
def test_text_handlers_operations(self):
"""Test TextHandlers list operations"""
handlers = TextHandlers([
TextHandler("First"),
TextHandler("Second"),
TextHandler("Third")
])
# Slicing should return TextHandlers
assert isinstance(handlers[0:2], TextHandlers)
# Get methods
assert handlers.get() == "First"
assert handlers.get("default") == "First"
assert TextHandlers([]).get("default") == "default"
def test_text_handlers_re(self):
"""Test TextHandlers.re() flattens results across all elements"""
handlers = TextHandlers([
TextHandler("a1 b2"),
TextHandler("c3 d4"),
])
results = handlers.re(r"[a-z]\d")
assert isinstance(results, TextHandlers)
assert len(results) == 4
assert results[0] == "a1"
assert results[3] == "d4"
def test_text_handlers_re_empty(self):
"""Test TextHandlers.re() on empty list"""
handlers = TextHandlers([])
results = handlers.re(r"\d+")
assert isinstance(results, TextHandlers)
assert len(results) == 0
def test_text_handlers_re_no_matches(self):
"""Test TextHandlers.re() when no element matches"""
handlers = TextHandlers([TextHandler("abc"), TextHandler("def")])
results = handlers.re(r"\d+")
assert len(results) == 0
def test_text_handlers_extract(self):
"""Test TextHandlers.extract() returns self"""
handlers = TextHandlers([TextHandler("a"), TextHandler("b")])
assert handlers.extract() is handlers
assert handlers.getall() is handlers
class TestSelectorsAdvanced:
"""Test advanced Selectors functionality"""
def test_selectors_filtering(self):
"""Test filtering operations on Selectors"""
html = """
<div>
<p class="highlight">Important</p>
<p>Regular</p>
<p class="highlight">Also important</p>
</div>
"""
page = Selector(html)
paragraphs = page.css("p")
# Filter by class
highlighted = paragraphs.filter(lambda p: p.has_class("highlight"))
assert len(highlighted) == 2
# Search for a specific element
found = paragraphs.search(lambda p: p.text == "Regular")
assert found is not None
assert found.text == "Regular"
def test_selectors_properties(self):
"""Test Selectors properties"""
html = "<div><p>1</p><p>2</p><p>3</p></div>"
page = Selector(html)
paragraphs = page.css("p")
assert paragraphs.first.text == "1"
assert paragraphs.last.text == "3"
assert paragraphs.length == 3
+64
View File
@@ -0,0 +1,64 @@
"""
Tests for Selectors.filter() method edge cases.
Target file: tests/parser/test_parser_advanced.py (append to TestAdvancedSelectors class)
"""
import pytest
from scrapling import Selector, Selectors
@pytest.fixture
def page():
html = """
<html><body>
<ul>
<li class="item" data-value="10">Apple</li>
<li class="item" data-value="5">Banana</li>
<li class="item" data-value="20">Cherry</li>
<li class="item disabled" data-value="0">Durian</li>
</ul>
</body></html>
"""
return Selector(html, adaptive=False)
class TestSelectorsFilter:
def test_filter_basic(self, page):
"""filter() should return only elements matching the predicate"""
items = page.css("li.item")
expensive = items.filter(lambda el: int(el.attrib.get("data-value", 0)) >= 10)
assert len(expensive) == 2
texts = expensive.getall()
assert any("Apple" in t for t in texts)
assert any("Cherry" in t for t in texts)
def test_filter_returns_empty_selectors_when_no_match(self, page):
"""filter() should return an empty Selectors (not None/exception) when nothing matches"""
items = page.css("li.item")
result = items.filter(lambda el: int(el.attrib.get("data-value", 0)) > 9999)
assert isinstance(result, Selectors)
assert len(result) == 0
assert result.first is None
def test_filter_all_pass(self, page):
"""filter() with always-True predicate should return all elements"""
items = page.css("li.item")
result = items.filter(lambda el: True)
assert len(result) == len(items)
def test_filter_chained(self, page):
"""filter() should be chainable - apply two filters in sequence"""
items = page.css("li.item")
# First: value > 0, then: not disabled
result = (
items
.filter(lambda el: int(el.attrib.get("data-value", 0)) > 0)
.filter(lambda el: not el.has_class("disabled"))
)
assert len(result) == 3 # Apple, Banana, Cherry (Durian is disabled AND value=0)
def test_filter_on_empty_selectors(self):
"""filter() on an already-empty Selectors should not raise"""
empty = Selectors()
result = empty.filter(lambda el: True)
assert isinstance(result, Selectors)
assert len(result) == 0