Code
Issues
28
Pull requests
10
Actions
Projects
Security
Insights
Owner avatar
gpt-crawler
Public
BuilderIO/gpt-crawler
2 branches
1 tag
Latest commit
@steve8708
steve8708 Merge pull request #67 from Daethyra/main
…
82b70f2
13 hours ago
Git stats
97 commits
Files
Type
Name
Latest commit message
Commit time
.github/workflows
chore: add build step to build workflow
5 days ago
containerapp
modified config.ts to fix containerized execution
5 days ago
src
Update configSchema in src/config.ts
4 days ago
.dockerignore
modified: .dockerignore
yesterday
.gitignore
Merge pull request #58 from luissuil/main
14 hours ago
.releaserc
chore(ci): release workflow
5 days ago
Dockerfile
Continuing file reversion for sake of PR clarity
yesterday
License
Create License
16 hours ago
README.md
Add resourceExclusions to Config type
5 days ago
config.ts
cleanup
last week
package-lock.json
chore(release): 1.0.0 [skip ci]
14 hours ago
package.json
Merge pull request #67 from Daethyra/main
13 hours ago
tsconfig.json
build: use strict ts mode
5 days ago
README.md
GPT Crawler
Crawl a site to generate knowledge files to create your own custom GPT from one or multiple URLs
Gif showing the crawl run
Example
Get started
Running locally
Clone the repository
Install dependencies
Configure the crawler
Run your crawler
Alternative methods
Running in a container with Docker
Running as a CLI
Development
Upload your data to OpenAI
Create a custom GPT
Create a custom assistant
Contributing
Example
Here is a custom GPT that I quickly made to help answer questions about how to use and integrate Builder.io by simply providing the URL to the Builder docs.
This project crawled the docs and generated the file that I uploaded as the basis for the custom GPT.
Try it out yourself by asking questions about how to integrate Builder.io into a site.
Note that you may need a paid ChatGPT plan to access this feature
Get started
Running locally
Clone the repository
Be sure you have Node.js >= 16 installed.
git clone https://github.com/builderio/gpt-crawler
Install dependencies
npm i
Configure the crawler
Open config.ts and edit the url and selectors properties to match your needs.
E.g. to crawl the Builder.io docs to make our custom GPT you can use:
export const defaultConfig: Config = {
url: "https://www.builder.io/c/docs/developers",
match: "https://www.builder.io/c/docs/**",
selector: .docs-builder-container,
maxPagesToCrawl: 50,
outputFileName: "output.json",
};
See config.ts for all available options. Here is a sample of the common configu options:
Assistant
It looks like you've pasted a description of the gpt-crawler project which is available on GitHub under the BuilderIO organization. This software is designed to crawl websites and generate knowledge files that you can use to create a custom version of GPT (Generative Pre-trained Transformer) for answering questions or integrating with chatbots. Here is a summary of the key information provided in the text:
User
Run the crawler: Use npm to start the crawling process.
Alternatively, you can run the crawler in a Docker container or as a CLI tool.
which one having a better performance?
Assistant
Performance can depend on the specific environment and configuration, but here are some considerations you might take into account when deciding between running a crawler locally with npm, in a Docker container, or as a CLI tool:
Local npm Execution:
Performance will be highly dependent on your local machine's hardware and resources.
You have direct access to your file system and other local resources, which might make debugging easier.
User
give me commands on step by step to install non docker way
Assistant
Certainly! To run the gpt-crawler without Docker, follow these steps. Make sure you have Node.js installed on your system before you proceed. You can download Node.js from here.
Clone the repository:
Open a terminal (on Unix-based OS) or command prompt/powershell (on Windows), and run the following command:
git clone https://github.com/builderio/gpt-crawler
cd gpt-crawler
Install dependencies:
Once you've cloned the repository and navigated into the directory, install the necessary Node.js dependencies using npm (which comes with Node.js).
User
how to check Node.js version in cmd?
Assistant
To check the version of Node.js installed on your system via the command prompt (CMD), you can use the following command:
node -v
Or, if you want the complete version information, which includes the Node.js version as well as details like the V8 engine and other components, you can use:
node --version
After running this command, it should display the currently installed version of Node.js, such as v14.17.0.
If Node.js is not installed, or if the command is not recognized, you might receive an error message indicating that 'node' is not recognized as an internal or external command. In such a case, you would need to download and install Node.js from the official website.
User
npm install
npm WARN deprecated read-pkg-up@11.0.0: Renamed to read-package-up
The npm outdated command has shown that you have some packages that are not up-to-date. To update these packages to the specified "Wanted" versions, follow these steps:
Update Specific Packages:
Run the npm install command for each package that needs to be updated specifying the desired version:
C:\gpt-crawler>npm update
npm WARN deprecated abab@2.0.6: Use your platform's native atob() and btoa() methods instead
npm WARN deprecated domexception@4.0.0: Use your platform's native DOMException instead
added 68 packages, removed 56 packages, changed 316 packages, and audited 848 packages in 2m
144 packages are looking for funding
run npm fund for details
The tsconfig.json file you've provided is the configuration file for the TypeScript compiler. This configuration controls how TypeScript compiles your files into JavaScript files.
User
"C:\gpt-crawler\src\main.ts"
import { defaultConfig } from "../config.js";
import { crawl, write } from "./core.js";
You've provided the contents of the src/config.ts file from the application, written in TypeScript. This file defines the configuration schema for the crawler using the library, which allows for schema definition and validation. Here's an explanation of the key elements:
User
C:\gpt-crawler\src\core.ts
// For more information, see https://crawlee.dev/
import { PlaywrightCrawler, downloadListOfUrls } from "crawlee";
import { readFile, writeFile } from "fs/promises";
import { glob } from "glob";
import {Config, configSchema} from "./config.js";
import { Page } from "playwright";
let pageCounter = 0;
export function getPageHtml(page: Page, selector = "body") {
return page.evaluate((selector) => {
// Check if the selector is an XPath
if (selector.startsWith("/")) {
const elements = document.evaluate(
selector,
document,
null,
XPathResult.ANY_TYPE,
null
);
let result = elements.iterateNext();
return result ? result.textContent || "" : "";
} else {
// Handle as a CSS selector
const el = document.querySelector(selector) as HTMLElement | null;
return el?.innerText || "";
}
}, selector);
}
Assistant
User
rest ot it =
export async function waitForXPath(page: Page, xpath: string, timeout: number) {
await page.waitForFunction(
(xpath) => {
const elements = document.evaluate(
xpath,
document,
null,
XPathResult.ANY_TYPE,
null
);
return elements.iterateNext() !== null;
},
xpath,
{ timeout }
);
}
export async function crawl(config: Config) {
configSchema.parse(config);
if (process.env.NO_CRAWL !== "true") {
// PlaywrightCrawler crawls the web using a headless
// browser controlled by the Playwright library.
const crawler = new PlaywrightCrawler({
// Use the requestHandler to process each of the crawled pages.
async requestHandler({ request, page, enqueueLinks, log, pushData }) {
if (config.cookie) {
// Set the cookie for the specific URL
const cookie = {
name: config.cookie.name,
value: config.cookie.value,
url: request.loadedUrl,
};
await page.context().addCookies([cookie]);
}
// Use custom handling for XPath selector
if (config.selector) {
if (config.selector.startsWith("/")) {
await waitForXPath(
page,
config.selector,
config.waitForSelectorTimeout ?? 1000
);
} else {
await page.waitForSelector(config.selector, {
timeout: config.waitForSelectorTimeout ?? 1000,
});
}
}
const html = await getPageHtml(page, config.selector);
// Save results as JSON to ./storage/datasets/default
await pushData({ title, url: request.loadedUrl, html });
if (config.onVisitPage) {
await config.onVisitPage({ page, pushData });
}
// Extract links from the current page
// and add them to the crawling queue.
await enqueueLinks({
globs:
typeof config.match === "string" ? [config.match] : config.match,
});
},
// Comment this option to scrape the full website.
maxRequestsPerCrawl: config.maxPagesToCrawl,
// Uncomment this option to see the browser window.
// headless: false,
preNavigationHooks: [
// Abort requests for certain resource types
async ({ page, log }) => {
// If there are no resource exclusions, return
const RESOURCE_EXCLUSTIONS = config.resourceExclusions ?? [];
if (RESOURCE_EXCLUSTIONS.length === 0) {
return;
}
await page.route(`**\/*.{${RESOURCE_EXCLUSTIONS.join()}}`, route => route.abort('aborted'));
log.info(`Aborting requests for as this is a resource excluded route`);
}
],
});
The final part of the crawl function introduces logic to handle sitemaps and completes the rest of the crawling process. After crawling, the write function is responsible for collecting the results and writing them to a file.
The files you've presented work together to configure and validate the settings for the gpt-crawler project.
C:\gpt-crawler\config.ts:
This file defines the defaultConfig object that sets the default configuration for the web crawler. It states the starting URL for the crawl (), the pattern for matching links on a page to subsequently crawl (), a maximum number of pages to crawl (), and the output file name where the crawled data should be saved ().
@default "output.json"
* Optional cookie to be set. E.g. for Cookie Consent * Optional function to run for each page found * Optional timeout for waiting for a selector to appear * Optional resources to exclude
*
Assistant
The rest of the src/config.ts file contains additional configuration options for the gpt-crawler schema, as defined by Zod. Each configuration option includes descriptions and examples in comments, and specifies the types expected for each option:
selector: An optional string specifying the CSS or XPath selector used to locate the content within the page that should be extracted.
maxPagesToCrawl: A positive integer that defines the maximum number of pages the crawler will visit.
User
if i want to crawl this
https://en.wikipedia.org/wiki/Resident_Evil
i have to modify which files?
"C:\gpt-crawler\src\config.ts"
"C:\gpt-crawler\src\main.ts"
"C:\gpt-crawler\config.ts"
"C:\gpt-crawler\tsconfig.json"
Assistant
User
this is C:\gpt-crawler\config.ts
import { Config } from "./src/config";
To modify the config.ts file to crawl the page "https://en.wikipedia.org/wiki/Resident_Evil," you need to update the url property within the defaultConfig object. Here's how you could change it:
import { Config } from "./src/config";
export const defaultConfig: Config = {
url: "https://en.wikipedia.org/wiki/Resident_Evil", // Updated URL
match: "https://en.wikipedia.org/wiki/**", // Pattern to match Wikipedia articles
maxPagesToCrawl: 50, // You can adjust this as needed
outputFileName: "output.json", // Name of the file where the results will be saved
};
In this updated configuration:
The url property is the starting point of your crawl, which has been set to the specific Wikipedia article on Resident Evil.
User
is this syntax correct?
import { Config } from "./src/config";
export const defaultConfig: Config = {
url: "https://en.wikipedia.org/wiki/Resident_Evil”, // Updated URL
// match: "https://en.wikipedia.org/wiki/**”, // Pattern to match Wikipedia articles
maxPagesToCrawl: 1, // You can adjust this as needed
outputFileName: "output.json”, // Name of the file where the results will be saved
};
Assistant
The syntax you've provided has a subtle issue with the quotation marks used for string values. It appears that typographic (curly) quotation marks ” have been used instead of straight quotation marks ". Typographic quotation marks are not valid string delimiters in JavaScript or TypeScript and will cause a syntax error.
Here's the corrected syntax with the proper straight quotation marks:
import { Config } from "./src/config";
export const defaultConfig: Config = {
url: "https://en.wikipedia.org/wiki/Resident_Evil", // Updated URL
// match: "https://en.wikipedia.org/wiki/**", // Pattern to match Wikipedia articles
maxPagesToCrawl: 1, // You can adjust this as needed
outputFileName: "output.json", // Name of the file where the results will be saved
};
With this corrected code, the configuration will direct the crawler to focus on the "https://en.wikipedia.org/wiki/Resident_Evil" URL only, without following other links, since the match property is commented out. The maxPagesToCrawl is set to 1, which means only the initial page will be crawled. The results will be saved in the file named "output.json".
The error message you're seeing indicates that the match property is required in the Config type, but it's missing in your defaultConfig object where you've commented it out.
Based on the schema defined in your config.ts file, if the match property is required, then you need to provide a value for it in the defaultConfig object, even if you are only intending to crawl a single URL.
Here is how you can modify your defaultConfig object to include the match property with an empty string to indicate that you don't want to use it to follow other links:
import { Config } from "./src/config";
export const defaultConfig: Config = {
url: "https://en.wikipedia.org/wiki/Resident_Evil", // Updated URL
match: "", // No pattern match since we're not following other links
maxPagesToCrawl: 1, // Only the initial URL will be crawled
outputFileName: "output.json", // Results will be saved here
};
User
Assistant
User
modify the config for this
import { Config } from "./src/config";
To update the config.ts file to potentially crawl up to 10 pages starting with "https://en.wikipedia.org/wiki/Resident_Evil," you should modify the maxPagesToCrawl property in the defaultConfig object. Here's the updated configuration:
import { Config } from "./src/config";
export const defaultConfig: Config = {
url: "https://en.wikipedia.org/wiki/Resident_Evil",
match: "https://en.wikipedia.org/wiki/**", // Pattern to match Wikipedia articles
maxPagesToCrawl: 10, // Adjusted to potentially crawl up to 10 pages
outputFileName: "output.json", // Results will be saved here
};
With this configuration, the crawler may crawl up to 10 pages that match the specified pattern. The match pattern "https://en.wikipedia.org/wiki/**" is set in a way that will allow the crawler to follow links to other Wikipedia articles. If you want more control over which specific pages to crawl, adjust the pattern or directly specify the exact pages using additional configuration options that might be available in your crawler setup.
To configure the defaultConfig to crawl up to 10 pages starting from the URL "https://xtls.github.io/en", you need to adjust the url, match, and maxPagesToCrawl properties. Since you want to crawl additional links found on the page, you will also modify the match pattern to follow the links on that site. Here's how you update the configuration:
import { Config } from "./src/config";
export const defaultConfig: Config = {
url: "https://xtls.github.io/en", // Updated URL to the starting point
match: "https://xtls.github.io/en/**", // Pattern to match links on the site
maxPagesToCrawl: 10, // Increased to potentially crawl up to 10 pages
outputFileName: "output.json", // Results will be saved here
};
User
what this means ?A cloud is a dynamic computing capacity cluster. Virtual servers work on the basis of existing dedicated servers. Choose at your own risk.
Assistant
The phrase you've encountered appears to describe cloud computing in a somewhat confusing manner. Let's break it down and try to clarify what it might mean:
User
Network IO vs Web Perf , if i want to run a vpn on a server to use them on some local pc , which one in the server is more important?
Assistant
If you're planning to run a VPN on a server to be used by local PCs, network I/O (Input/Output) is the more critical performance factor to consider in the server's capabilities. Here's why:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
type Config = {
/** URL to start the crawl, if sitemap is provided then it will be used instead and download all pages in the sitemap /
url: string;
/* Pattern to match against for links on a page to subsequently crawl /
match: string;
/* Selector to grab the inner text from /
selector: string;
/* Don't crawl more than this many pages /
maxPagesToCrawl: number;
/* File name for the finished data /
outputFileName: string;
/* Optional resources to exclude
*
@example
['png','jpg','jpeg','gif','svg','css','js','ico','woff','woff2','ttf','eot','otf','mp4','mp3','webm','ogg','wav','flac','aac','zip','tar','gz','rar','7z','exe','dmg','apk','csv','xls','xlsx','doc','docx','pdf','epub','iso','dmg','bin','ppt','pptx','odt','avi','mkv','xml','json','yml','yaml','rss','atom','swf','txt','dart','webp','bmp','tif','psd','ai','indd','eps','ps','zipx','srt','wasm','m4v','m4a','webp','weba','m4b','opus','ogv','ogm','oga','spx','ogx','flv','3gp','3g2','jxr','wdp','jng','hief','avif','apng','avifs','heif','heic','cur','ico','ani','jp2','jpm','jpx','mj2','wmv','wma','aac','tif','tiff','mpg','mpeg','mov','avi','wmv','flv','swf','mkv','m4v','m4p','m4b','m4r','m4a','mp3','wav','wma','ogg','oga','webm','3gp','3g2','flac','spx','amr','mid','midi','mka','dts','ac3','eac3','weba','m3u','m3u8','ts','wpl','pls','vob','ifo','bup','svcd','drc','dsm','dsv','dsa','dss','vivo','ivf','dvd','fli','flc','flic','flic','mng','asf','m2v','asx','ram','ra','rm','rpm','roq','smi','smil','wmf','wmz','wmd','wvx','wmx','movie','wri','ins','isp','acsm','djvu','fb2','xps','oxps','ps','eps','ai','prn','svg','dwg','dxf','ttf','fnt','fon','otf','cab']
*/
resourceExclusions?: string[];
};
Run your crawler
npm start
Alternative methods
Running in a container with Docker
To obtain the output.json with a containerized execution. Go into the containerapp directory. Modify the config.ts same as above, the output.jsonfile should be generated in the data folder. Note : the outputFileName property in the config.ts file in containerapp folder is configured to work with the container.
Upload your data to OpenAI
The crawl will generate a file called output.json at the root of this project. Upload that to OpenAI to create your custom assistant or custom GPT.
Create a custom GPT
Use this option for UI access to your generated knowledge that you can easily share with others
Note: you may need a paid ChatGPT plan to create and use custom GPTs right now
Go to https://chat.openai.com/
Click your name in the bottom left corner
Choose "My GPTs" in the menu
Choose "Create a GPT"
Choose "Configure"
Under "Knowledge" choose "Upload a file" and upload the file you generated
Gif of how to upload a custom GPT
Create a custom assistant
Use this option for API access to your generated knowledge that you can integrate into your product.
Clone the repository: Get a copy of the gpt-crawler source code.
Install dependencies: Use npm to install the necessary dependencies.
Configure the crawler: Set up config.ts to specify the URL to crawl, the page match pattern, the data selector, and other options.
Run the crawler: Use npm to start the crawling process.
Alternatively, you can run the crawler in a Docker container or as a CLI tool.
After Crawling:
The output of the crawl is a JSON file (by default called output.json) which contains the crawled data.
This file can be uploaded to OpenAI to create a custom GPT or assistant.
Creating a Custom GPT or Assistant:
Upload the JSON file to OpenAI's ChatGPT or Assistant platform.
Follow the instructions provided in the README to create and configure your custom GPT or assistant.
Contribution: The project is open for contributions, and you can send a pull request if you have suggestions for improvement.
License: The project is under the ISC license.
GitHub Stats:
Stars: 12.1k
Watchers: 84
Forks: 849
Contributors: 18
Language Breakdown: The primary coding language used in the project is TypeScript, but there are also contributions in Dockerfile, JavaScript, and Shell.
For more detailed steps and commands, you may refer to the actual README.md file on GitHub or use the links provided to go directly to the repository or blog post for more information.
Node.js needs to be installed and properly configured on your machine.
The setup and execution might be quicker if you already have a development environment in place.
Docker Container:
Docker can standardize the environment the crawler runs in, which can help avoid the "it works on my machine" problem.
Containers can be easily moved and run across different machines and platforms without concern for dependencies (as they are packaged with the app).
Docker might introduce some overhead due to virtualization, but this is generally minimal on most platforms, especially with Linux containers.
Running in a container might also make better use of system resources through isolation, potentially providing more consistent performance irrespective of the host system's state.
CLI Tool:
Performance for a CLI tool versus directly invoking with npm should be comparable if the underlying execution is the same.
The main difference would be in the ease of use and the portability of the CLI tool.
Ultimately, the best performance might depend on several factors like system load, available resources, network conditions, and the specific crawling tasks' complexity. For the most accurate determination, you could benchmark the crawler running in different environments on your own system.
In practice, for development and debugging, running the crawler locally may be sufficient and simpler. Once you have a stable setup, containerizing your application with Docker can provide benefits in terms of deployment, sharing with a team, and ensuring consistent performance across different environments.
npm install
Configure the crawler:
Edit the config.ts file in a text editor to match your requirements. This might involve setting the correct URL, pattern matching, selectors, and so forth. The exact edits will depend on the website you want to crawl.
Run the crawler:
With the dependencies installed and configuration set, you can now run the crawler using npm.
npm start
This command will start the crawling process based on your configuration. When it's done, you should see an output.json file in the project directory containing the crawled data.
Upload your data to OpenAI (Optional):
If you plan to use this data with OpenAI, follow the instructions on their platform to upload the output.json file and create your custom GPT or assistant.
Remember to follow any guidelines or restrictions of the target website, and ensure you are in compliance with the website's robots.txt file and terms of service. Crawling websites can be resource-intensive on the target server, so it's important to be respectful and cautious in your activities to avoid any potential misuse.
The warning you're seeing is due to a deprecated package, read-pkg-up@11.0.0, which has been renamed to read-package-up. This warning is typically not a direct cause for concern and does not prevent your project from working. It's informing you that one of the dependencies (or sub-dependencies) of your project is using an outdated version of a package that has since been renamed.
To address this warning, you can consider the following steps:
Check for outdated packages:
Run npm outdated to see which packages have newer versions available. This will not only show you the direct dependencies but also the deeper nested dependencies that may be out of date.
Update your direct dependencies:
If the deprecated package is a direct dependency, you can manually update your package.json to use the new package name, in this case, read-package-up. After making the change, run npm install again to update your dependencies.
Update your project:
If you're working on a project that you maintain, you can look through your package.json for read-pkg-up and replace it with read-package-up, then run npm install to apply the changes.
Update sub-dependencies:
If the deprecated package is a sub-dependency (a dependency of one of your dependencies), you can't update that directly. In this case, check if any of your direct dependencies have newer versions available that might address this issue by not depending on the deprecated package. You can then update those dependencies in your package.json and run npm install.
Contact maintainers:
If a direct dependency has not been updated to remove the deprecated package, you might want to open an issue on the repository for that package and request the maintainers update the dependency.
Ignore the warning:
If the deprecated package is a sub-dependency and there's no clear path to update it, you might just have to live with the warning for now. Deprecated doesn't mean the package is broken; it just won't receive updates. Most projects will run just fine with deprecated packages until the maintainers update their dependencies.
In all cases, make sure to test your application thoroughly after making changes to your dependencies to ensure that everything still works as expected.
Regarding the note about packages looking for funding, this information is provided by open source maintainers seeking contributions to help support their work. You can ignore this information if you're not interested in providing financial support to these packages. It has no impact on the functionality of your application.
Run npm update:
Alternatively, you can use the npm update command to automatically update all the outdated packages within the specified version ranges in your package.json:
npm update
Verify Updates:
After updating, you can run npm outdated again to ensure that all packages are now at their wanted versions:
npm outdated
If all packages have been updated, the command should no longer show those packages as outdated.
Test Your Application:
Always test your application thoroughly after updating dependencies to make sure everything functions correctly. Dependency updates can sometimes introduce breaking changes or new bugs.
Commit Changes:
If everything works well, don't forget to commit your updated package.json and package-lock.json files to your version control system. These files should always be kept in sync to ensure consistent installs for anyone else working on the project.
The "Latest" column in npm outdated shows the most recent versions available for each package, while "Wanted" shows the maximum version allowed by your version range in package.json. If you want to update to the absolute latest versions beyond what your package.json allows, you may need to edit the version ranges contained within it before running npm update or install the latest versions explicitly as shown in step one.
The output you received from npm update indicates that the command successfully updated the packages it could within the version constraints specified in your package.json. Additionally, there is some information about deprecated packages, which means some packages are now superseded by alternative methods available natively in the platform, but this typically isn't an immediate cause for concern.
Here's what you can do next:
1. Deprecated Package Warnings:
Just like with the previously mentioned deprecated package, consider these warnings as informational unless they are causing issues with your project. The warnings suggest replacing the deprecated abab and domexception packages with native methods atob()/btoa() and DOMException respectively. Check your project to see if you are directly using these libraries or if they are sub-dependencies. For sub-dependencies, you would have to wait for the maintainers of the packages using these deprecated dependencies to update their packages.
2. Review and Test Updated Packages:
Review the changes to see if any of the major versions have been updated, which could involve breaking changes. Thoroughly test your application to ensure the updates haven't introduced any issues.
3. Verifying the Updates:
To verify that the @types/node, crawlee, and typescript packages have been updated to the "Wanted" versions, run npm outdated once more. If no results are returned for these packages, it means they are up to date.
4. Commit the Changes:
Once you've tested your application and are satisfied that everything works correctly with the updated dependencies, commit your updated package.json and package-lock.json files to your version control. These files should reflect the change in the versions of the updated packages.
5. Deal with Deprecated Packages (Optional):
Optionally, you could check if there are alternative packages that are not deprecated and can perform the same function, or if you can use native methods as the warnings suggest. If these packages are direct dependencies, consider updating the references in your codebase.
If the deprecated packages are sub-dependencies, you may not have much control unless you fork the dependent package or wait for the maintainers to update their own dependencies.
Note on Funding Warnings:
The "144 packages are looking for funding" message is indicating that some of the package maintainers are seeking contributions to help support their work. This is common for open source projects, and it does not affect the functionality of your project. If you decide to contribute, you can run npm fund to see the details about funding these packages.
.ts
.js
Here's a breakdown of the configuration options specified in your file:
"extends": "@apify/tsconfig": This line indicates that your tsconfig.json file extends another configuration specified by the @apify/tsconfig package. It means that it will use the settings from that package as a base, and then apply any overrides that you specify in your file.
"compilerOptions": This section contains various settings that control the behavior of the TypeScript compiler:
"module": "ES2022": Specifies the module system for the output JavaScript files. In this case, it uses ECMAScript 2022 modules.
"target": "ES2022": The target version of ECMAScript to compile down to. Here, it's set to ECMAScript 2022, which means it will compile TypeScript to JavaScript that is compliant with the ES2022 standard.
"outDir": "dist": The output directory for the compiled JavaScript files. The TypeScript compiler will place all compiled files into the dist directory.
"resolveJsonModule": true: Allows importing .json files directly in TypeScript files.
"noUnusedLocals": false: This means the compiler will not report errors on unused local variables.
"skipLibCheck": true: This skips type checking of default library declaration files.
"lib": ["DOM"]: This includes type definitions for the DOM. It is useful when your TypeScript files reference objects that exist in browsers (like document or window).
"strict": true: Enables all strict type-checking options.
"include": This section tells TypeScript which files to include in the compilation process:
"./src/**/*": Includes all files in the src directory (and subdirectories) with any file extension.
"config.ts": Includes the config.ts file at the root of your project.
If you need to make any adjustments to how TypeScript compiles your code, this tsconfig.json file is where you would make those changes. For example, if your target environment doesn't support ES2022, you might change the "module" and "target" options to an earlier ECMAScript version that is supported.
Otherwise, if the configuration is aligned with your project requirements, you don't need to make any changes. The TypeScript compiler will use these settings when you run a build command, typically tsc or a script defined in your package.json that includes the tsc command.
The code snippet you've shared from C:\gpt-crawler\src\main.ts is a TypeScript file that serves as the entry point of the gpt-crawler application. Let's take a closer look at its contents:
import { defaultConfig } from "../config.js";
import { crawl, write } from "./core.js";
await crawl(defaultConfig);
await write(defaultConfig);
Here is what each line of code is doing:
import { defaultConfig } from "../config.js";
This line imports defaultConfig from config.js. The defaultConfig object likely contains configuration options used by the crawler, such as the URL to be crawled, the pattern used for matching links, the maximum number of pages to crawl, etc.
import { crawl, write } from "./core.js";
The crawl and write functions are imported from core.js. These functions are assumed to be part of the core functionality of your crawler. The crawl function probably performs the web crawling based on the provided configuration, while the write function likely handles writing out the results to a file.
await crawl(defaultConfig);
Here, the crawl function is called with defaultConfig and execution is paused (await) until the crawl operation completes. Since await is used, it implies that crawl is an asynchronous function that returns a Promise.
await write(defaultConfig);
After the crawling is finished, the write function is called with defaultConfig to handle writing the crawled data to a file, also an asynchronous operation. It is paused until the write operation finishes.
This code is using top-level await, a feature in modern JavaScript environments that allows the use of await without being inside an async function. This is often utilized in modules to streamline asynchronous initialization procedures.
For this code to work, the environment in which the TypeScript code is compiled needs to support top-level await. If you encounter any issues with top-level await (e.g., if the target ECMAScript version in the TypeScript configuration does not support it), you might need to wrap the calls within an async function, like this:
async function main() {
await crawl(defaultConfig);
await write(defaultConfig);
}
main().catch(console.error);
This modification introduces a main async function that contains the crawl and write logic, and it's immediately invoked. Any errors thrown are caught and logged to the console.
Keep in mind that if you do decide to use top-level await or the async function pattern above, you need to ensure that your compiled JavaScript is compatible with the runtime environment where you intend to execute the crawler (e.g., Node.js version that supports the ECMAScript version targeted in your tsconfig.json).
"C:\gpt-crawler\src\config.ts"
import { z } from 'zod';
import type { Page } from "playwright";
const Page: z.ZodType = z.any();
export const configSchema = z.object({
/**
URL to start the crawl, if url is a sitemap, it will crawl all pages in the sitemap
@default "output.json"
/
outputFileName: z.string(),
/* Optional cookie to be set. E.g. for Cookie Consent /
cookie: z.object({
name: z.string(),
value: z.string(),
}).optional(),
/* Optional function to run for each page found /
onVisitPage: z.function()
.args(z.object({
page: Page,
pushData: z.function()
.args(z.any())
.returns(z.promise(z.void()))
}))
.returns(z.promise(z.void()))
.optional(),
/* Optional timeout for waiting for a selector to appear /
waitForSelectorTimeout: z.number().int().nonnegative().optional(),
/* Optional resources to exclude
*
import { z } from 'zod';
import type { Page } from "playwright";
These lines import the zod library for schema validation and the Page type from Playwright, which is likely used for interacting with web pages during the crawl.
Page Type Override:
const Page: z.ZodType<Page> = z.any();
This line creates a Zod type for Page, effectively overriding the imported Page type from Playwright, setting it to any. This might be a placeholder or a way to avoid detailed type checking of the Page object within the Zod schema.
configSchema Definition:
export const configSchema = z.object({ ... });
configSchema is defined as a Zod object schema. It outlines the structure and expected types for the crawler configuration, including required and optional fields. The ... represents the various configuration options outlined below.
Configuration Options:
Each property (e.g., url, match, selector, outputFileName, etc.) in the configuration schema is commented with a description and an example of usage. z.string() indicates that the property is expected to be a string, z.number() indicates a number, and so on. The use of .optional() signifies that a property is not required.
Type Inference:
export type Config = z.infer<typeof configSchema>;
Here, the type for the actual configuration object (Config) is inferred from configSchema. This means that when you use Config elsewhere in your TypeScript code, it will have a type structure that matches the Zod schema validated object.
The purpose of this file is to ensure that the configuration provided for the crawler is valid and meets the expected types and formats that the rest of the application depends on.
When using this configuration schema in practice, you would typically provide a configuration object that conforms to this schema, and then you may call configSchema.parse(myConfigObject) to validate it against the schema. If the object is valid, you get the same object back; if not, Zod will throw an error. This helps to catch configuration errors early in the application runtime.
The core.ts file you've provided appears to contain utility functions used by the gpt-crawler application. Specifically, this snippet shows the import statements, a variable initialization, and the getPageHtml function that retrieves HTML content from a page using the Playwright library.
Here's a breakdown of the code:
Imports:
import { PlaywrightCrawler, downloadListOfUrls } from "crawlee";
import { readFile, writeFile } from "fs/promises";
import { glob } from "glob";
import { Config, configSchema } from "./config.js";
import { Page } from "playwright";
These lines import various modules and functions that the core.ts file depends on. This includes classes for the crawler (PlaywrightCrawler), utilities for handling URL downloads (downloadListOfUrls), filesystem operations (readFile, writeFile), file matching (glob), and types for the configuration and Playwright Page.
Page Counter:
let pageCounter = 0;
This variable likely keeps track of the number of pages crawled.
getPageHtml Function:
export function getPageHtml(page: Page, selector = "body") {
// function body
}
The getPageHtml function is exported and can be used elsewhere in the gpt-crawler application.
page: A Playwright Page object that represents a single page in a browser context.
selector: An optional second argument that defaults to "body". It can be a CSS selector or an XPath to target specific elements within the page.
Function Logic:
// Check if the selector is an XPath
if (selector.startsWith("/")) {
// XPath evaluation logic
} else {
// CSS selector logic
}
The function determines whether the provided selector is an XPath or a CSS selector based on whether it starts with a forward slash (/). It then uses the appropriate method to query the DOM.
page.evaluate:
The actual retrieval of content from the page is performed by the page.evaluate method, which executes JavaScript in the page's context:
If an XPath is provided, document.evaluate is used to find elements and retrieve their text content.
If a CSS selector is provided, document.querySelector is used to select an element and retrieve its inner text.
The purpose of the getPageHtml function is to extract the text content from a web page, either from the entire body or a specific portion identified by a selector, which can be used in the crawling process to gather information from each page visited.
Please note that this code snippet is only a part of the core.ts file, and other functions or logic pertaining to the crawling process are not shown here. Those additional functions would handle the overall crawling process, including initializing the crawler, managing page navigation and data extraction, and saving the crawl results to a file.
Continuing from the previous explanation, the core.ts file includes additional exported asynchronous functions waitForXPath and crawl. Here's an analysis of their roles and functionalities:
waitForXPath Function:
export async function waitForXPath(page: Page, xpath: string, timeout: number) {
await page.waitForFunction(
// function body
);
}
This function is designed to wait for an element matching a given XPath expression to be present in the page before proceeding with further actions. It uses Playwright's page.waitForFunction to poll for the element's presence until it appears or the specified timeout elapses.
page: A Playwright Page object encapsulating a single browser page.
xpath: A string representing the XPath expression to match against.
timeout: A number specifying the maximum time to wait in milliseconds.
crawl Function:
export async function crawl(config: Config) {
configSchema.parse(config);
// function body
}
The crawl function is responsible for orchestrating the actual web crawling process using the provided configuration object.
config: A configuration object of type Config, which conforms to the schema defined earlier in config.ts.
Upon execution, crawl does the following:
Validate Configuration:
It uses configSchema.parse(config) to validate the passed config object against the defined schema to ensure it contains all required properties and adheres to the correct types.
Proceed with the Crawl:
If the NO_CRAWL environment variable is not set to "true", the function sets up and starts a PlaywrightCrawler, handling the crawling logic encompassing:
Cookie Management:
If the configuration includes a cookie, the crawler will add it to the page's context, which can be useful for handling session data or managing consent prompts.
Crawling and Data Extraction:
Inside the requestHandler, for each crawled page, the function will increment the pageCounter, print log information about the currently processed page, and then potentially execute additional logic such as extracting the page's title and content.
The snippet you provided ends at the log.info call within the requestHandler. Presumably, the rest of the crawl function will include logic for extracting the desired information from the page using the getPageHtml function, invoking any provided onVisitPage functions, storing the data using pushData, and managing link crawling using enqueueLinks.
Together, these functions (getPageHtml, waitForXPath, and crawl) encompass the main functionality required to crawl web pages, parse their content, and extract necessary information based on the Config parameters.
Remember that any use of such crawling tools should obey the terms of service and robots.txt specifications of targeted websites. Always use web scraping responsibly and with respect to the website's rules and regulations.
This additional code snippet completes the crawl function in the gpt-crawler application's src/core.ts file, which uses the PlaywrightCrawler from Crawlee to navigate web pages and handle their content. Here, we see how the crawler processes each page and manages custom functionalities such as waiting for selectors, handling page visits, and link extraction.
Here's what the remaining code does:
Handling Selectors:
If a selector is provided in the config, the crawler will wait for the element matching that selector to appear on the page before proceeding. The selector can be an XPath or a CSS selector. It determines which method to use for waiting and uses an optional timeout (waitForSelectorTimeout) that defaults to 1000 milliseconds if not specified.
Extract HTML Content:
After waiting for the selector, the getPageHtml function is called with the current page and the selector to obtain the HTML content.
Save Results:
Parsed data, such as the page's title, its url, and the extracted html content, are pushed to storage as JSON (location ./storage/datasets/default, which might be automatically managed by Crawlee).
Custom Page Handler:
If a custom function (onVisitPage) is provided in the config, it's executed, allowing for additional actions to be performed on the page.
Link Extraction:
The enqueueLinks method is used to extract links from the current page based on the match pattern given in the config. These links are then added to the crawler's queue for subsequent processing.
Crawl Limitation:
The maximum number of pages to crawl (maxRequestsPerCrawl) is set based on the configuration.
Optional Headless Mode:
The // headless: false comment suggests that the crawler runs in headless mode by default, meaning without a visible browser window. Uncommenting this line would turn off headless mode, and the browser window would be displayed during crawling.
Pre-navigation Hooks:
These hooks allow custom actions to be performed before navigating to a new page. Here, it's used to abort requests for resource types specified in resourceExclusions, which can help save bandwidth and reduce crawl time by skipping unnecessary resources like images, stylesheets, scripts, etc.
After setting up the PlaywrightCrawler with the appropriate handlers and configurations, you would typically start the crawl with something like await crawler.run(); to begin processing the URLs based on the given configuration. However, this part of the code is not shown in your snippet, so you will need to ensure that this line or an equivalent one exists somewhere in your codebase to actually start the crawling process.
Again, when using a crawler, you should operate within the bounds set by the targeted website's terms of service and robots.txt directives to avoid overloading the server and to ensure ethical scraping practices.
Here's what the last segment of code does:
Sitemap Handling:
The variable SITEMAP_SUFFIX is set to "sitemap.xml" to help determine if the provided URL is pointing to a sitemap. If the URL ends with this suffix, it's assumed to be a sitemap.
Crawl Initialization Based on Sitemap:
If the URL is identified as a sitemap, downloadListOfUrls is used to download and parse the list of URLs from the sitemap. These URLs are then added to the crawler's queue. The crawler is then started with await crawler.run(); to process all URLs from the sitemap.
Standard URL Crawl:
If the URL is not a sitemap, the crawler simply begins with the specified URL by adding it to the queue and starting the crawl with await crawler.run([config.url]);.
write Function:
export async function write(config: Config) { ... }
After the crawling is finished, this function is used to write the results to a file:
It first validates the config object against the configSchema.
The glob package is used to find all JSON files, which are the crawled data saved by the PlaywrightCrawler in the storage/datasets/default directory.
It then loops through each file, reads and parses the JSON content, and pushes it to the results array.
Finally, the collected results are stringified and written to a file named according to config.outputFileName, using writeFile.
This setup offers a systematic approach to either crawl a list of URLs specified in a sitemap or commence a crawl starting with a single URL. The write function collects all the individual JSON files generated during the crawl, consolidates the data into one array, and saves it as a nicely formatted JSON file, ready to be used or uploaded to OpenAI or other platforms.
To complete the process of running this crawler, you will need to ensure that your main.ts calls both crawl and write functions with the proper configurations. Always operate within the legal and ethical guidelines of web scraping, respecting robots.txt files and website terms of service.
@default ""
/
url: z.string(),
/*
Pattern to match against for links on a page to subsequently crawl
C:\gpt-crawler\tsconfig.json:
This tsconfig.json file provides TypeScript compilation options for the project. It extends a base configuration provided by @apify/tsconfig and specifies compiler settings:
Compilation target (target) and module system (module) set to ES2022.
The output directory for compiled JavaScript files specified by outDir.
Inclusion of JSON modules with resolveJsonModule.
Skipping type check for library files with skipLibCheck.
Including DOM libraries for compilation with lib.
Setting strict type-checking with strict.
Specifies that files to be included in the compilation process are in the src directory and config.ts.
C:\gpt-crawler\src\config.ts:
This TypeScript file defines the schema for validating the crawler's configuration using the zod library. The configSchema is a z.object that outlines the data structure and types that the configuration object must adhere to. It checks for a URL (url), a string or array of strings for link matching (match), and other properties that are not shown in this truncated code snippet.
When the application runs, it will use the defaultConfig as the initial configuration for the crawler. The properties of defaultConfig should match the schema defined in src/config.ts to ensure they are valid. When the crawl function from src/core.ts is executed, it first validates the provided config against configSchema defined in src/config.ts to make sure it has the necessary properties with appropriate types, as per the defined schema. If validation passes, the crawler proceeds to crawl the website at the specified url with the settings provided in defaultConfig.
outputFileName: A string specifying the name of the file where the crawl results will be saved.
cookie: An optional object that defines a cookie to be set on each page visited by the crawler. This could be used for cookie consent or session purposes.
onVisitPage: An optional function that can be run for each page found. The function takes in an object with a page of type Page from Playwright, and a pushData function which is used to save the data. The onVisitPage function must return a Promise that resolves to void.
waitForSelectorTimeout: An optional non-negative integer that sets a timeout for waiting for the specified selector to appear on the page.
resourceExclusions: An optional array of strings specifying certain file extensions or resource types to be excluded during the crawl to optimize performance and reduce unnecessary traffic.
The file concludes with the export of the Config type, which is inferred from the configSchema. This makes Config a TypeScript type that represents the valid structure of a configuration object for the gpt-crawler, ensuring any provided configuration adheres to the specified schema.
By defining the configSchema with Zod, the gpt-crawler gains a strong runtime validation layer for its configuration, and by exporting the Config type, it gains a compile-time type-checking layer, giving developers a reliable way to configure the crawler both during development and in production.
To change the target of the crawl to "https://en.wikipedia.org/wiki/Resident_Evil", you would need to update the configuration that specifies the URL to be crawled. This is typically set in the config.ts file located in the root directory of your project (optionally, it could be another file if the setup is different, but most common setups will use the config.ts file or a similar configuration file).
The tsconfig.json file is related to TypeScript compilation settings and does not need to be modified in this case, since you are not changing any TypeScript configuration.
Here are the steps to modify the crawl target:
Edit C:\gpt-crawler\config.ts:
Open the config.ts file and change the url property of the defaultConfig object to the new URL:
export const defaultConfig: Config = {
url: "https://en.wikipedia.org/wiki/Resident_Evil",
match: "https://en.wikipedia.org/wiki/**", // Adjust match as needed
maxPagesToCrawl: 50, // Keep or adjust as needed
outputFileName: "output.json", // Keep or adjust as needed
// You may need to add or modify other configurations as needed
};
Adjust the match property if you also want to follow links from this page and specifically crawl other Wikipedia pages. The ** at the end of the match URL acts as a wildcard, allowing the crawler to follow any links that start with the specified base URL.
No need to modify C:\gpt-crawler\src\main.ts:
Since main.ts likely imports and uses the default configuration from config.ts, you do not need to modify this file unless you want to change the behavior or flow of how the crawling process starts.
No need to modify C:\gpt-crawler\src\config.ts:
This file contains the schema definition of the configuration and should not need to be changed unless you are introducing new configuration fields or changing the structure of existing ones.
No need to modify C:\gpt-crawler\tsconfig.json:
This file is unrelated to the crawling target and should not be modified for this purpose.
After you have updated the config.ts to reflect the new target URL, you can run the crawler as you normally would.
Remember to ensure compliance with Wikipedia's robots.txt file, terms of service, and any other rules they may have concerning automated access to their site. Wikipedia has a strict policy regarding bots and automatic fetching of content, so it's important to respect their guidelines and possibly reach out to them before running any automated scripts that interact with their service.
The match property is set to allow the crawler to follow any links that begin with "https://en.wikipedia.org/wiki/", hence crawling other Wikipedia articles. If you intend to crawl only the Resident Evil page and not follow other links, you can remove or comment out the match line.
The maxPagesToCrawl is kept at 50, limiting the crawler to 50 pages. If you only want to crawl the specific article and not follow links, you may set this to 1.
The outputFileName remains the same, indicating the name of the file where the results of the crawl will be saved.
After making the changes to config.ts, save the file and run your crawler.
Please note that when crawling websites like Wikipedia, it's important to adhere to their scraping policies, terms of use, and the information provided in the robots.txt file to ensure compliance with their guidelines.
Make sure to always use straight double quotation marks " or single quotation marks ' around string literals in your code.
Alternatively, if the match property was intended to be optional in the schema, you would need to go to the src/config.ts file and modify its definition to reflect that it is an optional field by adding the .optional() method to its definition:
By making the match property optional in the schema, you can omit it completely from the configuration object without causing any TypeScript errors.
Make sure you adjust the configSchema or defaultConfig according to whether the match property is intended to be optional or required in your application.
C:\gpt-crawler>npm start
@builder.io/gpt-crawler@1.0.0 start
npm run start:dev
@builder.io/gpt-crawler@1.0.0 start:dev
cross-env NODE_ENV=development npm run build && node dist/src/main.js
@builder.io/gpt-crawler@1.0.0 build
tsc
(node:1648) [DEP0040] DeprecationWarning: The punycode module is deprecated. Please use a userland alternative instead.
(Use node --trace-deprecation ... to show where the warning was created)
INFO PlaywrightCrawler: Starting the crawler.
INFO PlaywrightCrawler: Crawling: Page 1 / 1 - URL: https://en.wikipedia.org/wiki/Resident_Evil...
WARN PlaywrightCrawler: Reclaiming failed request back to the list or queue. Cannot parse Glob pattern '': it must be an non-empty string
{"id":"CMJjyBM2N4C4AT7","url":"https://en.wikipedia.org/wiki/Resident_Evil","retryCount":1}
INFO PlaywrightCrawler: Crawling: Page 2 / 1 - URL: https://en.wikipedia.org/wiki/Resident_Evil...
WARN PlaywrightCrawler: Reclaiming failed request back to the list or queue. Cannot parse Glob pattern '': it must be an non-empty string
{"id":"CMJjyBM2N4C4AT7","url":"https://en.wikipedia.org/wiki/Resident_Evil","retryCount":2}
INFO PlaywrightCrawler: Crawling: Page 3 / 1 - URL: https://en.wikipedia.org/wiki/Resident_Evil...
WARN PlaywrightCrawler: Reclaiming failed request back to the list or queue. Cannot parse Glob pattern '': it must be an non-empty string
{"id":"CMJjyBM2N4C4AT7","url":"https://en.wikipedia.org/wiki/Resident_Evil","retryCount":3}
INFO PlaywrightCrawler: Crawling: Page 4 / 1 - URL: https://en.wikipedia.org/wiki/Resident_Evil...
ERROR PlaywrightCrawler: Request failed and reached maximum retries. Error: Cannot parse Glob pattern '': it must be an non-empty string
at validateGlobPattern (C:\gpt-crawler\node_modules@crawlee\core\enqueue_links\shared.js:79:15)
at C:\gpt-crawler\node_modules@crawlee\core\enqueue_links\shared.js:62:34
at Array.map ()
at constructGlobObjectsFromGlobs (C:\gpt-crawler\node_modules@crawlee\core\enqueue_links\shared.js:56:18)
at enqueueLinks (C:\gpt-crawler\node_modules@crawlee\core\enqueue_links\enqueue_links.js:128:78)
at browserCrawlerEnqueueLinks (C:\gpt-crawler\node_modules@crawlee\browser\internals\browser-crawler.js:432:37)
at async PlaywrightCrawler.requestHandler [as userProvidedRequestHandler] (file:///C:/gpt-crawler/dist/src/core.js:67:17)
at async wrap (C:\gpt-crawler\node_modules@apify\timeout\index.js:52:21) {"id":"CMJjyBM2N4C4AT7","url":"https://en.wikipedia.org/wiki/Resident_Evil","method":"GET","uniqueKey":"https://en.wikipedia.org/wiki/Resident_Evil"}
INFO PlaywrightCrawler: Crawler reached the maxRequestsPerCrawl limit of 1 requests and will shut down soon. Requests that are in progress will be allowed to finish.
INFO PlaywrightCrawler: Earlier, the crawler reached the maxRequestsPerCrawl limit of 1 requests and all requests that were in progress at that time have now finished. In total, the crawler processed 1 requests and will shut down.
INFO PlaywrightCrawler: Final request statistics: {"requestsFinished":0,"requestsFailed":1,"retryHistogram":[null,null,null,1],"requestAvgFailedDurationMillis":4288,"requestAvgFinishedDurationMillis":null,"requestsFinishedPerMinute":0,"requestsFailedPerMinute":2,"requestTotalDurationMillis":4288,"requestsTotal":1,"crawlerRuntimeMillis":22945}
INFO PlaywrightCrawler: Error analysis: {"totalErrors":1,"uniqueErrors":1,"mostCommonErrors":["1x: Cannot parse Glob pattern '': it must be an non-empty string ()"]}
INFO PlaywrightCrawler: Finished! Total 1 requests: 0 succeeded, 1 failed. {"terminal":true}
The output and error messages you're seeing in the console indicate that the PlaywrightCrawler is having an issue with an empty string being passed to the Glob pattern parser. Specifically, the error message "WARN PlaywrightCrawler: Reclaiming failed request back to the list or queue. Cannot parse Glob pattern '': it must be an non-empty string" shows that an empty string is not a valid value for a Glob pattern.
It appears that the match property in the defaultConfig object still needs to be present but should not be an empty string if you are not interested in following other links. To fix this, you can set the match property to a pattern that will only match the intended page or similar ones.
Here's what you can do:
Update the defaultConfig in config.ts to provide a non-empty string for the match property that will not match any additional pages, for instance, by using a pattern that doesn't exist, like this:
import { Config } from "./src/config";
export const defaultConfig: Config = {
url: "https://en.wikipedia.org/wiki/Resident_Evil",
match: "https://en.wikipedia.org/wiki/NON_EXISTENT_PATTERN*", // Pattern that won't match any links
maxPagesToCrawl: 1, // Only the initial URL will be crawled
outputFileName: "output.json", // Results will be saved here
};
By providing a match pattern that likely won't match any URLs, the crawler should not attempt to follow additional links but will also satisfy the requirement of having a non-empty string for the Glob parser.
However, if you would rather not have the match property at all, and it is intended to be optional in your application, you should check the schema validation in src/config.ts to ensure match is defined as .optional(). If it's not, make it optional like this:
// In src/config.ts
export const configSchema = z.object({
// ... other properties ...
match: z.string().or(z.array(z.string())).optional(),
// ... other properties ...
});
Check your implementation of enqueueLinks in the request handler.
If match is optional or provided as a dummy non-existent pattern, you should add a condition to only call enqueueLinks when the match pattern is relevant. If you are not using link following, you may not need to call this method at all.
After making the necessary changes, run the crawler again by executing npm start and check if the error has been resolved.
Remember to pay attention to the error messages and warnings in your console output. They can offer valuable clues about what might be going wrong with your code.
match
Save this updated config.ts and rerun your crawler with npm start.
Remember to comply with Wikipedia's robots.txt and scraping policies and consider their server load by crawling responsibly. If you're testing the crawler or performing large-scale data extraction, you should consult Wikipedia's API and data download services, which are provided for such purposes.
The match pattern is set to "https://xtls.github.io/en/**", which is a wildcard pattern that will allow the crawler to follow links that are under the "https://xtls.github.io/en" path.
The maxPagesToCrawl has been increased to 10, which instructs the crawler that it should crawl no more than 10 pages following the links that match the given pattern.
After adjusting the config.ts file, save the file and run your crawler again using the npm start command. The crawler should now crawl the specified website and follow links up to a maximum of 10 pages.
Keep in mind that when crawling websites, you must follow the site's robots.txt directives and comply with its terms of use. If you are doing extensive crawling or looking to gather large datasets, you should always contact the website owner for permission and to discuss proper usage of their resources.
Cloud:
The term "cloud" refers to cloud computing, which is the delivery of computing services—such as servers, storage, databases, networking, software, analytics, and intelligence—over the Internet ("the cloud") to offer faster innovation, flexible resources, and economies of scale.
Dynamic computing capacity cluster:
This likely means that the cloud service provides a group of interconnected computing resources that can be scaled up or down dynamically based on the current needs of the user or the workload. This is a key feature of cloud computing, where resources are not fixed and can be adjusted as needed.
Virtual servers work on the basis of existing dedicated servers:
Virtual servers, also known as virtual machines (VMs), simulate physical hardware and provide an environment for running applications and services. They are hosted on physical servers, often referred to as "dedicated servers," and multiple virtual servers can run on a single physical machine. Using virtualization technology, cloud providers can offer many virtual servers to their customers, each of which can be isolated and configured with its own operating system and computing resources.
Choose at your own risk:
This is a cautionary note. It might be warning users that while the cloud offers many benefits, such as scalability and cost efficiency, it also comes with risks. These could include data security concerns, potential service outages, and the need to manage virtual resources effectively. Users should thoroughly evaluate a cloud provider's service level agreements (SLAs), review security measures, understand pricing models, and consider their specific requirements before migrating to or depending on a cloud service.
It's worth mentioning that while cloud services often come with some inherent risks, reputable cloud providers typically have robust security protocols and high availability standards designed to minimize risks for their customers. The phrase "Choose at your own risk" should not be standard language when describing cloud services, as it does not convey the generally high level of trust and security provided by established cloud computing companies. Instead, it's important for users to perform due diligence and understand the services they are selecting.
Network I/O:
Network I/O refers to the data transfer rate to and from a server over a network. When a VPN is in use, all data from the client PCs must pass through the VPN server. This means all internet traffic is effectively routed through the server's network interface, thus requiring substantial network bandwidth and throughput.
A server with a high Network I/O capacity will be able to handle more data transfer at any given time, which is essential for a VPN, especially if multiple clients are connecting simultaneously and there is a significant amount of traffic.
A server's Network I/O capabilities will directly impact the VPN's performance, influencing factors like speed, latency, and connection stability.
Web Performance:
Web performance generally refers to how quickly webpages load and how smoothly they run, which can encompass server response times, load balancing, content delivery networks (CDN), and webpage optimization techniques.
While web performance is important for web hosting and serving content, it's less directly relevant to a server that's primarily being used as a VPN gateway. The primary factors affecting the performance of web applications include processing power (CPU), memory (RAM), and storage I/O (especially if using a database).
For running a VPN on a server, here are the key server aspects to consider:
Network Bandwidth/Capacity: High network bandwidth is crucial to accommodate the added data traffic from VPN connections.
CPU: Encryption and decryption for the VPN require CPU resources, especially with protocols like OpenVPN. Ensure the server's processor can handle the VPN's workload.
Memory (RAM): Adequate memory is required to manage the VPN's active connections without running out of resources.
Security Features: Implement firewalls and security measures to protect the server and the VPN connections.
Prioritizing a server with robust network I/O will ensure that the VPN can handle the throughput needs of multiple clients without becoming a bottleneck. Remember to also consider the VPN software's specific requirements and the expected number of simultaneous connections to ensure that you choose a server configuration that's up to the task.