Skip to content
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

Fix to chicago library spyder #1133

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

Conversation

lilyhuang-github
Copy link

@lilyhuang-github lilyhuang-github commented Nov 15, 2024

Summary

Issue: #N/A
There's an issue with the Chicago Library spyder where if there's multiple dates with the strong tag then it'd go with the last one which currently causes an issue with the website if ran.

Checklist

All checks are run in GitHub Actions. You'll be able to see the results of the checks at the bottom of the pull request page after it's been opened, and you can click on any of the specific checks listed to see the output of each step and debug failures.

  • [ x] Tests are implemented
  • [x ] All tests are passing
  • [x ] Style checks run (see documentation for more details)
  • [x ] Style checks are passing
  • [x ] Code comments from template removed

Summary by CodeRabbit

  • New Features

    • Improved parsing logic for meeting data, enhancing accuracy in extracting meeting information.
    • Updated handling of HTTP requests for agenda and minutes links.
  • Bug Fixes

    • Adjusted year extraction to ensure correct year is captured from response headers.
    • Refined item iteration to skip irrelevant meeting items.
  • Refactor

    • Enhanced method signatures for better session management and data parsing.

the last item extracted causes an issue when there's multiple items with
the strong css, like with the current chicago library website.
Copy link

coderabbitai bot commented Nov 15, 2024

Walkthrough

The changes in the ChiLibrarySpider class within the city_scrapers/spiders/chi_library.py file involve updates to the constructor and several parsing methods. The constructor now accepts a session parameter for HTTP requests. The parsing logic has been refined to ensure accurate extraction of meeting data, including adjustments to how the year is captured and how start dates are parsed. The handling of links has also been improved by incorporating session-based requests to check the status of agenda and minutes URLs.

Changes

File Change Summary
city_scrapers/spiders/chi_library.py - Updated constructor to accept a session parameter.
- Adjusted year extraction logic in the parse method.
- Refined loop to skip items without strong tags.
- Changed index in _parse_start method from [-1] to [0] for date string extraction.
- Updated _parse_links method to use session for GET requests and check status codes.

Poem

In the library where stories abound,
A spider weaves, with data profound.
With sessions in tow, it scours the land,
Parsing the meetings, so deftly and grand.
From strong tags it gathers, with care it will find,
The tales of the city, all intertwined! 🐇📚


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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

@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

🧹 Outside diff range and nitpick comments (2)
city_scrapers/spiders/chi_library.py (2)

Line range hint 77-81: Critical: Incomplete fix for multiple dates in strong tags

While the change from [-1] to [0] addresses the immediate issue, it might still miss additional meeting dates when multiple strong tags are present. We should handle all dates found in strong tags.

Consider this approach:

-        dt_str = item.css("strong::text").extract()[0]
-        return datetime.datetime.strptime(
-            "{} {}".format(re.sub(r"[,\.]", "", dt_str), year), "%A %B %d %I %p %Y"
-        )
+        dates = []
+        for dt_str in item.css("strong::text").extract():
+            try:
+                date = datetime.datetime.strptime(
+                    "{} {}".format(re.sub(r"[,\.]", "", dt_str), year),
+                    "%A %B %d %I %p %Y"
+                )
+                dates.append(date)
+            except ValueError:
+                continue
+        if not dates:
+            raise ValueError("No valid dates found in strong tags")
+        return dates[0]  # Return the first valid date found

Line range hint 83-102: Improve robustness of link validation

The current implementation could benefit from better error handling and performance optimizations.

Consider these improvements:

     def _parse_links(self, start_time):
         """Check if agenda and minutes are valid URLs, add to documents if so"""
         agenda_url = (
             "https://www.chipublib.org/news/board-of-directors-"
             "meeting-agenda-{}-{date.day}-{date.year}/"
         ).format(
             start_time.strftime("%B").lower(),
             date=start_time,
         )
         minutes_url = agenda_url.replace("agenda", "minutes")
-        agenda_res = self.session.get(agenda_url)
-        minutes_res = self.session.get(minutes_url)
+        documents = []
+        timeout = 10  # seconds
+        
+        def check_url(url, doc_type):
+            try:
+                res = self.session.get(url, timeout=timeout)
+                if res.status_code == 200:
+                    documents.append({"href": url, "title": doc_type})
+            except (requests.RequestException, requests.Timeout):
+                self.logger.warning(f"Failed to fetch {doc_type} URL: {url}")
+
+        check_url(agenda_url, "Agenda")
+        check_url(minutes_url, "Minutes")
-        documents = []
-        if agenda_res.status_code == 200:
-            documents.append({"href": agenda_url, "title": "Agenda"})
-        if minutes_res.status_code == 200:
-            documents.append({"href": minutes_url, "title": "Minutes"})
         return documents
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5993e2d and f711be6.

📒 Files selected for processing (1)
  • city_scrapers/spiders/chi_library.py (1 hunks)
🔇 Additional comments (2)
city_scrapers/spiders/chi_library.py (2)

Line range hint 16-21: LGTM: Good practice to inject the session dependency

The session injection allows for better testing and performance through connection reuse.


Line range hint 1-102: Verify integration with the scraping framework

Let's ensure the changes are properly integrated with the framework and covered by tests.

✅ Verification successful

Implementation is properly integrated and well-tested

The verification shows:

  • Complete test coverage exists in tests/test_chi_library.py with comprehensive test cases for all attributes
  • The spider follows the framework's patterns by:
    • Properly extending CityScrapersSpider
    • Using framework constants (BOARD, TENTATIVE)
    • Following the expected Meeting item structure
    • Including proper mocking and test utilities from the core framework
  • The implementation matches the framework's requirements for parsing meetings and yielding standardized Meeting items

The changes are well-integrated with the scraping framework and have thorough test coverage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for spider usage and test coverage

# Check for spider usage in tests
echo "Checking for test coverage..."
rg -l "ChiLibrarySpider" tests/

# Check for similar patterns in other spiders
echo "Checking for similar patterns in other spiders..."
rg -l "strong::text" city_scrapers/spiders/

# Check for existing test cases with multiple dates
echo "Checking for test cases with multiple dates..."
rg -A 5 "multiple.*dates" tests/

Length of output: 454


Script:

#!/bin/bash
# Let's examine the test file and spider implementation patterns

# Check the test implementation
echo "Examining test implementation..."
cat tests/test_chi_library.py

# Check for similar spider patterns in the framework
echo "Checking spider patterns..."
ast-grep --pattern 'class $_Spider(CityScrapersSpider) {
  $$$
  def parse($_, $_) {
    $$$
  }
  $$$
}'

# Check core spider implementation
echo "Checking core spider implementation..."
fd "core" --type f --exec rg -l "CityScrapersSpider"

Length of output: 2611

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