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

This commit is contained in:
xiaoxue
2026-05-24 23:06:32 +08:00
commit 2b4682de8e
764 changed files with 98522 additions and 0 deletions
@@ -0,0 +1,54 @@
import asyncio
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import TypedDict
from fastapi import FastAPI
from crawlee.crawlers import ParselCrawler, ParselCrawlingContext
class State(TypedDict):
"""State available in the app."""
crawler: ParselCrawler
requests_to_results: dict[str, asyncio.Future[dict[str, str]]]
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[State]:
# Start up code that runs once when the app starts
# Results will be stored in this dictionary
requests_to_results = dict[str, asyncio.Future[dict[str, str]]]()
crawler = ParselCrawler(
# Keep the crawler alive even when there are no more requests to process now.
# This makes the crawler wait for more requests to be added later.
keep_alive=True
)
# Define the default request handler, which will be called for every request.
@crawler.router.default_handler
async def request_handler(context: ParselCrawlingContext) -> None:
context.log.info(f'Processing {context.request.url} ...')
title = context.selector.xpath('//title/text()').get() or ''
# Extract data from the page and save it to the result dictionary.
requests_to_results[context.request.unique_key].set_result(
{
'title': title,
}
)
# Start the crawler without awaiting it to finish
crawler.log.info(f'Starting crawler for the {app.title}')
run_task = asyncio.create_task(crawler.run([]))
# Make the crawler and the result dictionary available in the app state
yield {'crawler': crawler, 'requests_to_results': requests_to_results}
# Cleanup code that runs once when the app shuts down
crawler.stop()
# Wait for the crawler to finish
await run_task
@@ -0,0 +1,58 @@
from __future__ import annotations
import asyncio
from uuid import uuid4
from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import HTMLResponse
import crawlee
from .crawler import lifespan
app = FastAPI(lifespan=lifespan, title='Crawler app')
@app.get('/', response_class=HTMLResponse)
def index() -> str:
return """
<!DOCTYPE html>
<html>
<body>
<h1>Scraper server</h1>
<p>To scrape some page, visit "scrape" endpoint with url parameter.
For example:
<a href="/scrape?url=https://www.example.com">
/scrape?url=https://www.example.com
</a>
</p>
</body>
</html>
"""
@app.get('/scrape')
async def scrape_url(request: Request, url: str | None = None) -> dict:
if not url:
return {'url': 'missing', 'scrape result': 'no results'}
# Generate random unique key for the request
unique_key = str(uuid4())
# Set the result future in the result dictionary so that it can be awaited
request.state.requests_to_results[unique_key] = asyncio.Future[dict[str, str]]()
# Add the request to the crawler queue
await request.state.crawler.add_requests(
[crawlee.Request.from_url(url, unique_key=unique_key)]
)
# Wait for the result future to be finished
result = await request.state.requests_to_results[unique_key]
# Clean the result from the result dictionary to free up memory
request.state.requests_to_results.pop(unique_key)
# Return the result
return {'url': url, 'scrape result': result}