상대 링크가 있는 웹사이트 크롤링
웹사이트를 크롤링할 때 크롤링하고자 하는 다양한 유형의 링크를 만날 수 있습니다.
이러한 링크를 쉽게 크롤링할 수 있도록 크롤러 컨텍스트에서 enqueueLinks()
메서드를 제공합니다.
이 메서드는 자동으로 링크를 찾아 크롤러의 RequestQueue
에 추가합니다.
상대 링크를 크롤링하기 위한 3가지 전략을 제공합니다:
All (또는 문자열"all" ): 도메인에 관계없이 발견된 모든 링크를 큐에 추가합니다.SameHostname (또는 문자열"same-hostname" ): 동일한 호스트네임의 모든 링크를 큐에 추가합니다. 기본 전략입니다.SameDomain (또는 문자열"same-domain" ): 서브도메인을 포함하여 동일한 도메인 이름을 가진 모든 링크를 큐에 추가합니다.
이 예제들에서는 CheerioCrawler
를 사용하지만,
PuppeteerCrawler
와
PlaywrightCrawler
에서도
동일한 방식으로 사용할 수 있는 동일한 메서드가 제공됩니다.
- 모든 링크
- 동일 호스트네임
- 동일 서브도메인
현재 크롤링 중인 사이트를 벗어나더라도 발견된 모든 URL이 이 전략과 일치합니다.
import { CheerioCrawler, EnqueueStrategy } from 'crawlee';
const crawler = new CheerioCrawler({
maxRequestsPerCrawl: 10, // 최대 10개의 요청 제한 (모든 링크를 크롤링하려면 사용하지 않음)
async requestHandler({ request, enqueueLinks, log }) {
log.info(request.url);
await enqueueLinks({
// 'all' 전략을 설정하면 찾은 모든 링크를 추가
strategy: EnqueueStrategy.All,
// 또는 문자열 'all'을 전달할 수도 있습니다
// strategy: 'all',
});
},
});
// 초기 요청으로 크롤러 실행
await crawler.run(['https://crawlee.dev']);
URL이 https://example.com
인 경우, enqueueLinks()
는 상대 URL과 동일한 호스트네임을 가리키는 URL과 일치합니다.
이는
enqueueLinks()
호출 시 기본 전략이므로 별도로 지정할 필요가 없습니다.
예를 들어 https://example.com/some/path
, /absolute/example
또는 ./relative/example
와 같은 하이퍼링크는 모두 이 전략과 일치합니다. 하지만 https://subdomain.example.com/some/path
와 같은 서브도메인 링크는 일치하지 않습니다.
import { CheerioCrawler, EnqueueStrategy } from 'crawlee';
const crawler = new CheerioCrawler({
maxRequestsPerCrawl: 10, // 최대 10개의 요청 제한 (모든 링크를 크롤링하려면 사용하지 않음)
async requestHandler({ request, enqueueLinks, log }) {
log.info(request.url);
await enqueueLinks({
// 'same-hostname' 전략을 설정하면 요청의 loadedUrl 또는 url과 동일한 호스트에 있는 모든 링크를 추가
strategy: EnqueueStrategy.SameHostname,
// 또는 문자열 'same-hostname'을 전달할 수도 있습니다
// strategy: 'same-hostname',
});
},
});
// 초기 요청으로 크롤러 실행
await crawler.run(['https://crawlee.dev']);
URL이 https://subdomain.example.com
인 경우, enqueueLinks()
는 서브도메인에 관계없이 상대 URL 또는 동일한 도메인 이름을 가리키는 URL과 일치합니다.
예를 들어 https://subdomain.example.com/some/path
, /absolute/example
또는 ./relative/example
와 같은 하이퍼링크뿐만 아니라 https://other-subdomain.example.com
또는 https://example.com
과 같은 다른 서브도메인이나 루트 도메인으로의 링크도 이 전략과 일치합니다.
import { CheerioCrawler, EnqueueStrategy } from 'crawlee';
const crawler = new CheerioCrawler({
maxRequestsPerCrawl: 10, // 최대 10개의 요청 제한 (모든 링크를 크롤링하려면 사용하지 않음)
async requestHandler({ request, enqueueLinks, log }) {
log.info(request.url);
await enqueueLinks({
// 'same-domain' 전략을 설정하면 요청의 loadedUrl 또는 url과 동일한 호스트에 있는 모든 링크를 추가
strategy: EnqueueStrategy.SameDomain,
// 또는 문자열 'same-domain'을 전달할 수도 있습니다
// strategy: 'same-domain',
});
},
});
// 초기 요청으로 크롤러 실행
await crawler.run(['https://crawlee.dev']);