059a708b6d
- A modern spider design that uses AnyIO and asyncio, yet it's very similar to Scrapy spiders API because it's the easiest design for users, and to make it easier for new users. - Spiders can have multiple sessions per crawl, and users decide which session to use with each request. - A scheduler system that uses heapq logic. - The user can set the number of concurrent requests for a spider globally or per domain. - The user can set a download delay to control the speed of the spider more. - There's a global function that can be overridden to handle errors for all requests. (Similar to errback in scrapy). - There's a spider argument to set the allowed domains for the spider to stay in. - Each spider has a very detailed crawl stats that can be accessed right away from the code after the crawl finishes. Same case with scraped items. - The whole spider as written as any other script and you just run it. No command-line arguments, and no need to run it from the terminal through the library like other known alternatives. - Each spider has its own logger that forces sessions to use it. - Each spider has functions to override that run before start and after close. - There's a spider argument to set the logging level and another one to make the spider write to a log file. - This is only the start. A lot more features are coming in the way.
46 lines
1.3 KiB
Python
46 lines
1.3 KiB
Python
import asyncio
|
|
from itertools import count
|
|
|
|
from scrapling.core.utils import log
|
|
from scrapling.spiders.request import Request
|
|
|
|
|
|
class Scheduler:
|
|
"""
|
|
Priority queue with URL deduplication. (heapq)
|
|
|
|
Higher priority requests are processed first.
|
|
Duplicate URLs are filtered unless dont_filter=True.
|
|
"""
|
|
|
|
def __init__(self):
|
|
self._queue: asyncio.PriorityQueue[tuple[int, int, Request]] = asyncio.PriorityQueue()
|
|
self._seen: set[str] = set()
|
|
self._counter = count()
|
|
|
|
async def enqueue(self, request: Request) -> bool:
|
|
"""Add a request to the queue."""
|
|
fingerprint = request._fp
|
|
|
|
if not request.dont_filter and fingerprint in self._seen:
|
|
log.debug("Dropped duplicate request: %s", request)
|
|
return False
|
|
|
|
self._seen.add(fingerprint)
|
|
|
|
# Negative priority so higher priority = dequeued first
|
|
await self._queue.put((-request.priority, next(self._counter), request))
|
|
return True
|
|
|
|
async def dequeue(self) -> Request:
|
|
"""Get the next request to process."""
|
|
_, _, request = await self._queue.get()
|
|
return request
|
|
|
|
def __len__(self) -> int:
|
|
return self._queue.qsize()
|
|
|
|
@property
|
|
def is_empty(self) -> bool:
|
|
return self._queue.empty()
|