@segress/google-search
v1.0.3
Published
Google search automation with reCAPTCHA solving capabilities
Maintainers
Readme
@segress/google-search
Google search automation library with automatic reCAPTCHA solving capabilities using cap.guru service.
Features
- 🔍 Automated Google Search: Search across multiple pages of results
- 🤖 Automatic reCAPTCHA Solving: Automatic captcha detection and solving using cap.guru API
- 🥷 Stealth Mode: Uses puppeteer-extra-plugin-stealth to avoid bot detection
- 📊 Position Tracking: Track domain positions for specific keywords
- 🔄 Recursive Monitoring: Sequential captcha checking (no overlapping intervals)
- 🎯 TypeScript Support: Full TypeScript definitions included
- 🔐 Secure API Key Management: Support for environment variables and direct passing
Installation
npm install @segress/google-searchConfiguration
⚠️ Required: Cap.guru API Key
This library requires a cap.guru API key for automatic captcha solving.
Method 1: Environment Variable (Recommended)
Create a .env file in your project root:
CAPGURU_API_KEY=your_api_key_hereMethod 2: Set Globally in Code
import { setCapGuruApiKey } from '@segress/google-search';
// Set once at application start
setCapGuruApiKey('your_api_key_here');Method 3: Pass to Session/Search
// Pass to browser session
const { browser, page } = await createBrowserSession({
capGuruApiKey: 'your_api_key_here'
});
// Or pass to specific search
await googleSearch(page, query, 3, {
capGuruApiKey: 'your_api_key_here'
});Getting cap.guru API Key
- Register at cap.guru
- Add funds to your account (minimum $1)
- Copy your API key from the dashboard
- Set it using one of the methods above
Usage
Basic Example
import { createBrowserSession, googleSearch, setCapGuruApiKey } from '@segress/google-search';
async function main() {
// Set API key (required!)
setCapGuruApiKey('your_api_key_here');
// Create browser session
const { browser, page, stopMonitoring } = await createBrowserSession({
debugLogging: true // Enable detailed logs
});
try {
// Search Google
const results = await googleSearch(page, 'your search query', 3, {
debugLogging: true // Enable search-specific logs
});
console.log(`Found ${results.searchResults.length} results`);
results.searchResults.forEach((result, index) => {
console.log(`${index + 1}. ${result.title}`);
console.log(` URL: ${result.url}`);
});
} finally {
await stopMonitoring();
await browser.close();
}
}
main().catch(console.error);Position Tracking Example
import { createBrowserSession, googleSearch, setCapGuruApiKey } from '@segress/google-search';
import * as dotenv from 'dotenv';
// Load environment variables
dotenv.config();
async function trackPositions() {
// Get API key from environment
const apiKey = process.env.CAPGURU_API_KEY;
if (!apiKey) {
throw new Error('CAPGURU_API_KEY not found in .env file');
}
// Create session with API key
const { browser, page, stopMonitoring } = await createBrowserSession({
debugLogging: true,
capGuruApiKey: apiKey
});
const targetDomain = 'example.com';
const keywords = ['keyword1', 'keyword2', 'keyword3'];
const results = [];
for (const keyword of keywords) {
const searchResults = await googleSearch(page, keyword, 3);
// Find position of target domain
const position = searchResults.searchResults.findIndex(r =>
r.url.includes(targetDomain)
) + 1;
results.push({
keyword,
position: position || 'Not found',
totalResults: searchResults.resultsCount
});
// Random delay between searches (2-5 seconds)
await new Promise(resolve =>
setTimeout(resolve, 2000 + Math.random() * 3000)
);
}
// Display results table
console.table(results);
await stopMonitoring();
await browser.close();
}Advanced Usage
See src/example.ts for a complete example with:
- Multiple keyword checking
- Results table with statistics
- Average position calculation
- Top positions tracking
API Reference
setCapGuruApiKey(apiKey: string)
Sets the global API key for cap.guru service.
Parameters:
apiKey: string- Your cap.guru API key
Throws:
- Error if API key is empty
createBrowserSession(options?)
Creates a new browser session with reCAPTCHA monitoring.
Parameters:
options.debugLogging?: boolean- Enable detailed logging (default: false)options.capGuruApiKey?: string- Cap.guru API key (overrides global setting)
Returns:
browser: Browser- Puppeteer browser instancepage: Page- Main page instancestopMonitoring: () => Promise<void>- Function to stop captcha monitoring
googleSearch(page, query, pages?, options?)
Performs Google search with automatic captcha handling.
Parameters:
page: Page- Puppeteer page instancequery: string- Search querypages?: number- Number of result pages to search (default: 1, max 100 results per page)options.debugLogging?: boolean- Enable search-specific loggingoptions.capGuruApiKey?: string- Cap.guru API key (overrides global setting)
Returns:
hasIndexation: boolean- Whether results were foundresultsCount: number- Total number of results reported by GooglesearchResults: Array- Parsed search results with title, URL, and snippetrawHtml?: string- Raw HTML of search pages
Environment Variables
Create a .env file in your project root:
# Required: Cap.guru API key
CAPGURU_API_KEY=your_api_key_here
# Optional: Enable debug logging
DEBUG_LOGGING=trueCaptcha Solving Process
The library handles reCAPTCHA automatically:
- Detection: Monitors page every second for captcha presence
- Checkbox Click: Automatically clicks the reCAPTCHA checkbox
- Image Challenge: Takes screenshot and sends to cap.guru API
- Solution Application: Clicks on coordinates returned by API
- Multi-round Solving: Handles dynamic captchas with multiple image sets
- Retry Logic: Up to 3 attempts with captcha reload on failure
Development
# Install dependencies
npm install
# Build the project
npm run build
# Run the example
npm run example
# Watch mode for development
npm run watch
# Type checking only
npm run typecheckTroubleshooting
"API key not set" Error
Make sure to either:
- Create a
.envfile withCAPGURU_API_KEY=your_key - Call
setCapGuruApiKey('your_key')before using - Pass
capGuruApiKeyoption to functions
"Failed to launch browser" Error
The library will automatically fallback to regular puppeteer if stealth mode fails.
Captcha Not Solving
- Check your cap.guru balance
- Ensure API key is valid
- Enable
debugLogging: trueto see detailed logs
License
MIT
Author
Deadgress
