Skip to content

Fix TypeError when keep_data_attributes=False by ensuring list concat… #1234

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

AdarsHH30
Copy link

@AdarsHH30 AdarsHH30 commented Jun 19, 2025

Summary

Fixes #1226: This PR resolves a TypeError that occurs when keep_data_attributes=False is passed in the CrawlerRunConfig. The issue was due to a list concatenation with a bool, which is now safely handled by converting False to an empty list before concatenation.


List of Files Changed and Why

  • path/to/affected_file.py – Added type-check and logic to ensure keep_attrs and keep_data_attributes are always treated as lists, preventing runtime errors during attribute removal.

  • test_keep_attrs_fix.py – Added a test script to verify that the fix works for edge cases like False, True, None, and missing keys.


How Has This Been Tested?

  • Manually tested using a standalone script with multiple edge cases for keep_attrs and keep_data_attributes.
  • Verified the bug no longer occurs.
  • Confirmed no side effects for valid inputs.

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation (N/A)
  • I have added/updated unit tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of attribute parameters to prevent errors when excluding or keeping specific HTML attributes during content scraping.
  • Style

    • Standardized use of double quotes in string literals and CSS selectors for consistency.
    • Improved formatting of error messages and method calls for better readability.

Copy link
Contributor

coderabbitai bot commented Jun 19, 2025

Walkthrough

The changes focus on standardizing string quoting to double quotes, improving code formatting, and enhancing defensive programming. The main functional update ensures that the keep_attrs and keep_data_attributes parameters in the _process_element method are always treated as lists, preventing type errors when boolean values are passed. No public API changes were made.

Changes

File(s) Change Summary
crawl4ai/content_scraping_strategy.py Standardized to double quotes, improved formatting, and enhanced error handling. Fixed bug in _process_element to ensure keep_attrs and keep_data_attributes are always lists before use, preventing type errors when booleans are passed.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ContentScrapingStrategy
    participant remove_unwanted_attributes

    User->>ContentScrapingStrategy: scrap(html, keep_attrs, keep_data_attributes)
    ContentScrapingStrategy->>ContentScrapingStrategy: _process_element(element, keep_attrs, keep_data_attributes)
    alt keep_attrs or keep_data_attributes is bool
        ContentScrapingStrategy->>ContentScrapingStrategy: Convert to list if not already
    end
    ContentScrapingStrategy->>remove_unwanted_attributes: remove_unwanted_attributes(element, keep_attrs + keep_data_attributes)
    remove_unwanted_attributes-->>ContentScrapingStrategy: Processed element
    ContentScrapingStrategy-->>User: Return processed data
Loading

Assessment against linked issues

Objective Addressed Explanation
Prevent "can only concatenate list (not 'bool') to list" error when keep_data_attributes=False (#1226)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes were found.

Poem

In fields of code where carrots grow,
A bug once nibbled, causing woe.
Now lists are checked, no bools in sight,
The code hops on, the fix is right!
With double quotes and tidy rows,
This bunny’s joy just overflows! 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
crawl4ai/content_scraping_strategy.py (1)

277-351: Consider refactoring to reduce complexity

While the quote consistency changes are good, this method has high complexity as noted by static analysis (21 local variables, 13 branches). Consider breaking this into smaller helper methods.

For example, you could extract header processing and row processing into separate methods:

+    def _extract_table_headers(self, table: Tag) -> list:
+        """Extract headers from table with colspan handling."""
+        headers = []
+        thead_rows = table.select("thead tr")
+        if thead_rows:
+            header_cells = thead_rows[0].select("th")
+            for cell in header_cells:
+                text = cell.get_text().strip()
+                colspan = int(cell.get("colspan", 1))
+                headers.extend([text] * colspan)
+        else:
+            first_row = table.select("tr:first-child")
+            if first_row:
+                for cell in first_row[0].select("th, td"):
+                    text = cell.get_text().strip()
+                    colspan = int(cell.get("colspan", 1))
+                    headers.extend([text] * colspan)
+        return headers
+
+    def _extract_table_rows(self, table: Tag, headers: list) -> list:
+        """Extract rows from table with colspan handling."""
+        # Implementation here...
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b4bb0cc and 07272d4.

📒 Files selected for processing (1)
  • crawl4ai/content_scraping_strategy.py (16 hunks)
🧰 Additional context used
🪛 Pylint (3.3.7)
crawl4ai/content_scraping_strategy.py

[refactor] 277-277: Too many local variables (21/15)

(R0914)


[refactor] 277-277: Too many branches (13/12)

(R0912)

🔇 Additional comments (11)
crawl4ai/content_scraping_strategy.py (11)

52-52: LGTM: Quote consistency improvement

Good practice to standardize on double quotes for string literals.


160-160: LGTM: Trailing comma addition

Adding the trailing comma improves maintainability and reduces diff noise when adding new items to the list.


213-276: LGTM: CSS selector quote consistency

The standardization to double quotes in CSS selectors and string literals improves code consistency. The logic for table data detection remains unchanged and correct.


793-814: Excellent bug fix for type safety

This change properly addresses the TypeError when keep_attrs or keep_data_attributes are passed as boolean values instead of lists. The implementation correctly handles all edge cases:

  • False → empty list []
  • True or other truthy single values → wrapped in list [value]
  • Already lists → unchanged
  • None or other falsy values → empty list []

This ensures safe concatenation with IMPORTANT_ATTRS + keep_attrs.


899-901: LGTM: Error message formatting improvement

The multi-line formatting improves readability of the error message.


950-952: LGTM: Consistent error logging format

The improved formatting for error logging maintains consistency with the project's logging patterns.


998-998: LGTM: Quote consistency in table exclusion check

Consistent with the overall double-quote standardization throughout the file.


1428-1428: LGTM: Mathematical calculation formatting

The spacing around the exponentiation operator improves readability.


1439-1443: LGTM: Multi-line formatting for complex expressions

Breaking the complex sum expression across multiple lines significantly improves readability.


1582-1592: LGTM: Improved error logging formatting

The multi-line formatting for error messages improves code readability and maintainability.


1712-1712: LGTM: Dictionary formatting consistency

Single-line dictionary formatting is appropriate for simple structures and maintains consistency.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant