同步完整源码 - 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,28 @@
import asyncio
from crawlee.request_loaders import RequestList
async def main() -> None:
# Open the request list, if it does not exist, it will be created.
# Leave name empty to use the default request list.
request_list = RequestList(
name='my-request-list',
requests=[
'https://apify.com/',
'https://crawlee.dev/',
'https://crawlee.dev/python/',
],
)
# Fetch and process requests from the queue.
while request := await request_list.fetch_next_request():
# Do something with it...
print(f'Processing {request.url}')
# And mark it as handled.
await request_list.mark_request_as_handled(request)
if __name__ == '__main__':
asyncio.run(main())
@@ -0,0 +1,46 @@
import asyncio
import logging
from crawlee import service_locator
from crawlee.request_loaders import RequestList
logging.basicConfig(level=logging.INFO, format='%(asctime)s-%(levelname)s-%(message)s')
logger = logging.getLogger(__name__)
# Disable clearing the `KeyValueStore` on each run.
# This is necessary so that the state keys are not cleared at startup.
# The recommended way to achieve this behavior is setting the environment variable
# `CRAWLEE_PURGE_ON_START=0`
configuration = service_locator.get_configuration()
configuration.purge_on_start = False
async def main() -> None:
# Open the request list, if it does not exist, it will be created.
# Leave name empty to use the default request list.
request_list = RequestList(
name='my-request-list',
requests=[
'https://apify.com/',
'https://crawlee.dev/',
'https://crawlee.dev/python/',
],
# Enable persistence
persist_state_key='my-persist-state',
persist_requests_key='my-persist-requests',
)
# We receive only one request.
# Each time you run it, it will be a new request until you exhaust the `RequestList`.
request = await request_list.fetch_next_request()
if request:
logger.info(f'Processing request: {request.url}')
# Do something with it...
# And mark it as handled.
await request_list.mark_request_as_handled(request)
if __name__ == '__main__':
asyncio.run(main())
@@ -0,0 +1,43 @@
import asyncio
from crawlee.crawlers import ParselCrawler, ParselCrawlingContext
from crawlee.request_loaders import RequestList
async def main() -> None:
# Create a static request list.
request_list = RequestList(['https://crawlee.dev', 'https://apify.com'])
# highlight-start
# Convert the request list to a request manager using the to_tandem method.
# It is a tandem with the default request queue.
request_manager = await request_list.to_tandem()
# highlight-end
# Create a crawler and pass the request manager to it.
crawler = ParselCrawler(
request_manager=request_manager,
max_requests_per_crawl=10, # Limit the max requests per crawl.
)
@crawler.router.default_handler
async def handler(context: ParselCrawlingContext) -> None:
context.log.info(f'Processing {context.request.url}')
# New links will be enqueued directly to the queue.
await context.enqueue_links()
# Extract data using Parsel's XPath and CSS selectors.
data = {
'url': context.request.url,
'title': context.selector.xpath('//title/text()').get(),
}
# Push extracted data to the dataset.
await context.push_data(data)
await crawler.run()
if __name__ == '__main__':
asyncio.run(main())
@@ -0,0 +1,44 @@
import asyncio
from crawlee.crawlers import ParselCrawler, ParselCrawlingContext
from crawlee.request_loaders import RequestList, RequestManagerTandem
from crawlee.storages import RequestQueue
async def main() -> None:
# Create a static request list.
request_list = RequestList(['https://crawlee.dev', 'https://apify.com'])
# Open the default request queue.
request_queue = await RequestQueue.open()
# And combine them together to a single request manager.
request_manager = RequestManagerTandem(request_list, request_queue)
# Create a crawler and pass the request manager to it.
crawler = ParselCrawler(
request_manager=request_manager,
max_requests_per_crawl=10, # Limit the max requests per crawl.
)
@crawler.router.default_handler
async def handler(context: ParselCrawlingContext) -> None:
context.log.info(f'Processing {context.request.url}')
# New links will be enqueued directly to the queue.
await context.enqueue_links()
# Extract data using Parsel's XPath and CSS selectors.
data = {
'url': context.request.url,
'title': context.selector.xpath('//title/text()').get(),
}
# Push extracted data to the dataset.
await context.push_data(data)
await crawler.run()
if __name__ == '__main__':
asyncio.run(main())
@@ -0,0 +1,30 @@
import asyncio
import re
from crawlee.http_clients import ImpitHttpClient
from crawlee.request_loaders import SitemapRequestLoader
async def main() -> None:
# Create an HTTP client for fetching the sitemap.
http_client = ImpitHttpClient()
# Create a sitemap request loader with filtering rules.
sitemap_loader = SitemapRequestLoader(
sitemap_urls=['https://crawlee.dev/sitemap.xml'],
http_client=http_client,
include=[re.compile(r'.*docs.*')], # Only include URLs containing 'docs'.
max_buffer_size=500, # Keep up to 500 URLs in memory before processing.
)
# We work with the loader until we process all relevant links from the sitemap.
while request := await sitemap_loader.fetch_next_request():
# Do something with it...
print(f'Processing {request.url}')
# And mark it as handled.
await sitemap_loader.mark_request_as_handled(request)
if __name__ == '__main__':
asyncio.run(main())
@@ -0,0 +1,45 @@
import asyncio
import logging
from crawlee import service_locator
from crawlee.http_clients import ImpitHttpClient
from crawlee.request_loaders import SitemapRequestLoader
logging.basicConfig(level=logging.INFO, format='%(asctime)s-%(levelname)s-%(message)s')
logger = logging.getLogger(__name__)
# Disable clearing the `KeyValueStore` on each run.
# This is necessary so that the state keys are not cleared at startup.
# The recommended way to achieve this behavior is setting the environment variable
# `CRAWLEE_PURGE_ON_START=0`
configuration = service_locator.get_configuration()
configuration.purge_on_start = False
async def main() -> None:
# Create an HTTP client for fetching sitemaps
# Use the context manager for `SitemapRequestLoader` to correctly save the state when
# the work is completed.
async with (
ImpitHttpClient() as http_client,
SitemapRequestLoader(
sitemap_urls=['https://crawlee.dev/sitemap.xml'],
http_client=http_client,
# Enable persistence
persist_state_key='my-persist-state',
) as sitemap_loader,
):
# We receive only one request.
# Each time you run it, it will be a new request until you exhaust the sitemap.
request = await sitemap_loader.fetch_next_request()
if request:
logger.info(f'Processing request: {request.url}')
# Do something with it...
# And mark it as handled.
await sitemap_loader.mark_request_as_handled(request)
if __name__ == '__main__':
asyncio.run(main())
@@ -0,0 +1,53 @@
import asyncio
import re
from crawlee.crawlers import ParselCrawler, ParselCrawlingContext
from crawlee.http_clients import ImpitHttpClient
from crawlee.request_loaders import SitemapRequestLoader
async def main() -> None:
# Create an HTTP client for fetching the sitemap.
http_client = ImpitHttpClient()
# Create a sitemap request loader with filtering rules.
sitemap_loader = SitemapRequestLoader(
sitemap_urls=['https://crawlee.dev/sitemap.xml'],
http_client=http_client,
include=[re.compile(r'.*docs.*')], # Only include URLs containing 'docs'.
max_buffer_size=500, # Keep up to 500 URLs in memory before processing.
)
# highlight-start
# Convert the sitemap loader into a request manager linked
# to the default request queue.
request_manager = await sitemap_loader.to_tandem()
# highlight-end
# Create a crawler and pass the request manager to it.
crawler = ParselCrawler(
request_manager=request_manager,
max_requests_per_crawl=10, # Limit the max requests per crawl.
)
@crawler.router.default_handler
async def handler(context: ParselCrawlingContext) -> None:
context.log.info(f'Processing {context.request.url}')
# New links will be enqueued directly to the queue.
await context.enqueue_links()
# Extract data using Parsel's XPath and CSS selectors.
data = {
'url': context.request.url,
'title': context.selector.xpath('//title/text()').get(),
}
# Push extracted data to the dataset.
await context.push_data(data)
await crawler.run()
if __name__ == '__main__':
asyncio.run(main())
@@ -0,0 +1,54 @@
import asyncio
import re
from crawlee.crawlers import ParselCrawler, ParselCrawlingContext
from crawlee.http_clients import ImpitHttpClient
from crawlee.request_loaders import RequestManagerTandem, SitemapRequestLoader
from crawlee.storages import RequestQueue
async def main() -> None:
# Create an HTTP client for fetching the sitemap.
http_client = ImpitHttpClient()
# Create a sitemap request loader with filtering rules.
sitemap_loader = SitemapRequestLoader(
sitemap_urls=['https://crawlee.dev/sitemap.xml'],
http_client=http_client,
include=[re.compile(r'.*docs.*')], # Only include URLs containing 'docs'.
max_buffer_size=500, # Keep up to 500 URLs in memory before processing.
)
# Open the default request queue.
request_queue = await RequestQueue.open()
# And combine them together to a single request manager.
request_manager = RequestManagerTandem(sitemap_loader, request_queue)
# Create a crawler and pass the request manager to it.
crawler = ParselCrawler(
request_manager=request_manager,
max_requests_per_crawl=10, # Limit the max requests per crawl.
)
@crawler.router.default_handler
async def handler(context: ParselCrawlingContext) -> None:
context.log.info(f'Processing {context.request.url}')
# New links will be enqueued directly to the queue.
await context.enqueue_links()
# Extract data using Parsel's XPath and CSS selectors.
data = {
'url': context.request.url,
'title': context.selector.xpath('//title/text()').get(),
}
# Push extracted data to the dataset.
await context.push_data(data)
await crawler.run()
if __name__ == '__main__':
asyncio.run(main())