Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: much more reliable pagination #331

Merged
merged 15 commits into from
Jan 13, 2025
Merged

feat: much more reliable pagination #331

merged 15 commits into from
Jan 13, 2025

Conversation

RohitR311
Copy link
Contributor

@RohitR311 RohitR311 commented Jan 9, 2025

Support bulk scraping data by fixing pagination selector logic

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced pagination functionality across the application
    • Improved selector generation and navigation handling
  • Improvements

    • Added more robust pagination tracking and navigation mechanisms
    • Implemented advanced selector chaining for complex page structures
    • Introduced socket-based pagination mode management
  • Bug Fixes

    • Prevented revisiting the same URLs during pagination
    • Added error handling for navigation attempts

The updates provide a more resilient and flexible pagination experience with better tracking and navigation capabilities.

@RohitR311 RohitR311 marked this pull request as draft January 9, 2025 11:32
Copy link

coderabbitai bot commented Jan 9, 2025

Walkthrough

The pull request introduces enhancements to pagination handling across multiple components of the application. Changes span the core interpretation logic, workflow generation, browser window interaction, and browser actions context. The modifications focus on improving URL navigation, selector generation, and pagination mode management. The updates aim to create a more robust and flexible pagination mechanism that can handle complex page structures and prevent potential navigation issues.

Changes

File Change Summary
maxun-core/src/interpret.ts Enhanced handlePagination method with:
- visitedUrls tracking
- Improved URL navigation logic
- Multiple selector iteration
- Enhanced error handling
- Detailed logging
server/src/workflow-management/classes/Generator.ts Added paginationMode property
- New socket event listener for setPaginationMode
- Enhanced generateSelector method for complex selector chaining
src/components/browser/BrowserWindow.tsx Added socket emission to reset pagination mode when element is selected
src/context/browserActions.tsx Added socket emission to activate pagination mode

Sequence Diagram

sequenceDiagram
    participant User
    participant BrowserWindow
    participant Socket
    participant WorkflowGenerator
    participant Interpreter

    User->>BrowserWindow: Initiate Pagination
    BrowserWindow->>Socket: setPaginationMode(true)
    Socket->>WorkflowGenerator: Update paginationMode
    WorkflowGenerator->>WorkflowGenerator: Prepare Complex Selectors
    User->>BrowserWindow: Select Element
    BrowserWindow->>Socket: setPaginationMode(false)
    Interpreter->>Interpreter: Navigate and Track URLs
Loading

Poem

🐰 Hop, hop, through pages we go,
Selectors dancing, URLs in tow
No more loops that spin and twirl
Pagination's magic now unfurls
A rabbit's guide to browsing's art! 🌐

Finishing Touches

  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@amhsirak amhsirak added the Type: Feature New features label Jan 9, 2025
@amhsirak amhsirak changed the title feat: support bulk scraping feat: much more reliable pagination Jan 9, 2025
@RohitR311 RohitR311 marked this pull request as ready for review January 13, 2025 06:55
@RohitR311 RohitR311 requested a review from amhsirak January 13, 2025 06:55
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (2)
maxun-core/src/interpret.ts (2)

Line range hint 688-747: Refactor load more button handling for better reliability.

The load more button handling has similar issues to the selector iteration and could be more reliable.

Issues to address:

  1. Duplicate code with selector iteration
  2. No maximum attempts for load more clicks
  3. No validation of new content loading

Apply this fix:

+const MAX_LOAD_MORE_ATTEMPTS = 5;
+const CONTENT_CHECK_TIMEOUT = 2000;
+
+async function validateNewContent(page: Page, previousHeight: number): Promise<boolean> {
+  await page.waitForTimeout(CONTENT_CHECK_TIMEOUT);
+  const currentHeight = await page.evaluate(() => document.body.scrollHeight);
+  return currentHeight > previousHeight;
+}

 case 'clickLoadMore':
+  let loadMoreAttempts = 0;
   while (true) {
+    if (loadMoreAttempts >= MAX_LOAD_MORE_ATTEMPTS) {
+      console.log('Max load more attempts reached');
+      const finalResults = await page.evaluate((cfg) => window.scrapeList(cfg), config);
+      allResults = allResults.concat(finalResults);
+      return allResults;
+    }

     // ... existing selector iteration code ...

     try {
-      await Promise.race([
-        loadMoreButton.click(),
-        loadMoreButton.dispatchEvent('click')
-      ]);
+      const clickResult = await Promise.race([
+        loadMoreButton.click().then(() => true),
+        loadMoreButton.dispatchEvent('click').then(() => true)
+      ]).catch(() => false);
+
+      if (!clickResult) {
+        console.log('Click failed');
+        loadMoreAttempts++;
+        continue;
+      }
+
+      const contentLoaded = await validateNewContent(page, previousHeight);
+      if (!contentLoaded) {
+        console.log('No new content loaded');
+        loadMoreAttempts++;
+        continue;
+      }
+
+      loadMoreAttempts = 0; // Reset counter on successful load
     } catch (error) {
       console.log('Both click attempts failed');
+      loadMoreAttempts++;
     }
   }
🧰 Tools
🪛 Biome (1.9.4)

[error] 601-601: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 602-602: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 623-623: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 628-628: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 636-636: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 659-659: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


Line range hint 581-747: Fix switch case variable declarations.

Static analysis indicates potential issues with variable declarations in switch cases. These declarations should be wrapped in blocks to prevent unintended access from other cases.

Apply this fix to all switch cases:

 case 'clickNext': {
   console.log("Page URL:", page.url());
   const pageResults = await page.evaluate((cfg) => window.scrapeList(cfg), config);
   // ... rest of the case
   break;
 }
 case 'clickLoadMore': {
   let loadMoreAttempts = 0;
   while (true) {
     // ... rest of the case
   }
   break;
 }
🧰 Tools
🪛 Biome (1.9.4)

[error] 601-601: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 602-602: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 623-623: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 628-628: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 636-636: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 659-659: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

🧹 Nitpick comments (2)
server/src/workflow-management/classes/Generator.ts (1)

710-728: Enhance selector chaining logic with error handling.

The selector chaining logic for pagination mode is well-structured but could benefit from additional error handling and validation.

Consider these improvements:

  1. Add null/undefined checks before accessing properties
  2. Add error handling for invalid selectors
  3. Consider deduplicating selectors in the chain
 if (this.paginationMode && selectorBasedOnCustomAction) {
   // Chain selectors in specific priority order
   const selectors = selectorBasedOnCustomAction;
+  const validSelectors = new Set<string>();
   const selectorChain = [
     selectors?.iframeSelector?.full,
     selectors?.shadowSelector?.full,
     selectors?.testIdSelector,
     selectors?.id,
     selectors?.hrefSelector,
     selectors?.accessibilitySelector,
     selectors?.attrSelector,
     selectors?.generalSelector
   ]
-    .filter(selector => selector !== null && selector !== undefined)
+    .filter(selector => {
+      try {
+        if (!selector) return false;
+        // Add to Set to deduplicate
+        return validSelectors.add(selector);
+      } catch (error) {
+        console.error(`Invalid selector: ${selector}`, error);
+        return false;
+      }
+    })
     .join(',');

   return selectorChain;
 }
maxun-core/src/interpret.ts (1)

Line range hint 550-616: Add timeout and retry mechanism for selector iteration.

While the selector iteration logic is robust, it could benefit from a timeout and retry mechanism.

Consider adding:

  1. Maximum retry attempts
  2. Exponential backoff
  3. Timeout for selector checks
+const MAX_RETRIES = 3;
+const BASE_TIMEOUT = 1000;

 let availableSelectors = config.pagination.selector.split(',');
+let retryCount = 0;

 for (let i = 0; i < availableSelectors.length; i++) {
   const selector = availableSelectors[i];
   try {
-    checkButton = await page.waitForSelector(selector, { state: 'attached' });
+    checkButton = await page.waitForSelector(selector, { 
+      state: 'attached',
+      timeout: BASE_TIMEOUT * Math.pow(2, retryCount)
+    });
     if (checkButton) {
       workingSelector = selector;
       break;
     }
   } catch (error) {
     console.log(`Selector failed: ${selector}`);
+    if (retryCount < MAX_RETRIES) {
+      retryCount++;
+      i--; // Retry the same selector
+      continue;
+    }
   }
+  retryCount = 0; // Reset for next selector
 }
🧰 Tools
🪛 Biome (1.9.4)

[error] 601-601: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 602-602: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 623-623: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 628-628: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 636-636: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 659-659: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 651ab19 and b5421f3.

📒 Files selected for processing (4)
  • maxun-core/src/interpret.ts (4 hunks)
  • server/src/workflow-management/classes/Generator.ts (3 hunks)
  • src/components/browser/BrowserWindow.tsx (1 hunks)
  • src/context/browserActions.tsx (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
maxun-core/src/interpret.ts

[error] 582-582: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 601-601: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 602-602: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 623-623: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 628-628: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 636-636: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 659-659: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

🔇 Additional comments (5)
src/context/browserActions.tsx (1)

57-57: LGTM! Socket emission for pagination mode.

The addition of socket?.emit('setPaginationMode', { pagination: true }) aligns with the PR's objective to enhance pagination functionality by properly managing the pagination state across components.

src/components/browser/BrowserWindow.tsx (1)

263-263: LGTM! Proper cleanup of pagination mode.

The addition of socket?.emit('setPaginationMode', { pagination: false }) ensures the pagination mode is properly reset after successfully selecting a pagination selector.

server/src/workflow-management/classes/Generator.ts (2)

67-68: LGTM! Pagination mode state tracking.

The addition of private paginationMode: boolean = false; provides proper state tracking for pagination mode.


125-127: LGTM! Socket event handler for pagination mode.

The socket event listener properly updates the pagination mode state based on received data.

maxun-core/src/interpret.ts (1)

548-549: LGTM! URL tracking to prevent infinite loops.

The addition of visitedUrls array helps prevent infinite loops by tracking previously visited pages.

Comment on lines +622 to +682
// const nextButton = await page.$(config.pagination.selector);
const nextButton = await page.$(workingSelector);
if (!nextButton) {
return allResults; // No more pages to scrape
}
await Promise.all([
nextButton.dispatchEvent('click'),
page.waitForNavigation({ waitUntil: 'networkidle' })
]);

const selectorIndex = availableSelectors.indexOf(workingSelector!);
availableSelectors = availableSelectors.slice(selectorIndex);

// await Promise.all([
// nextButton.dispatchEvent('click'),
// page.waitForNavigation({ waitUntil: 'networkidle' })
// ]);

const previousUrl = page.url();
visitedUrls.push(previousUrl);

try {
// Try both click methods simultaneously
await Promise.race([
Promise.all([
page.waitForNavigation({ waitUntil: 'networkidle', timeout: 30000 }),
nextButton.click()
]),
Promise.all([
page.waitForNavigation({ waitUntil: 'networkidle', timeout: 30000 }),
nextButton.dispatchEvent('click')
])
]);
} catch (error) {
// Verify if navigation actually succeeded
const currentUrl = page.url();
if (currentUrl === previousUrl) {
console.log("Previous URL same as current URL. Navigation failed.");
}
}

const currentUrl = page.url();
if (visitedUrls.includes(currentUrl)) {
console.log(`Detected navigation to a previously visited URL: ${currentUrl}`);

// Extract the current page number from the URL
const match = currentUrl.match(/\d+/);
if (match) {
const currentNumber = match[0];
// Use visitedUrls.length + 1 as the next page number
const nextNumber = visitedUrls.length + 1;

// Create new URL by replacing the current number with the next number
const nextUrl = currentUrl.replace(currentNumber, nextNumber.toString());

console.log(`Navigating to constructed URL: ${nextUrl}`);

// Navigate to the next page
await Promise.all([
page.waitForNavigation({ waitUntil: 'networkidle' }),
page.goto(nextUrl)
]);
}
}

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle race conditions in navigation logic.

The navigation logic has potential race conditions and could benefit from more robust error handling.

Issues to address:

  1. Race condition between click methods
  2. Lack of proper error handling for navigation failures
  3. Potential infinite loop in URL construction

Apply this fix:

-try {
-  await Promise.race([
-    Promise.all([
-      page.waitForNavigation({ waitUntil: 'networkidle', timeout: 30000 }),
-      nextButton.click()
-    ]),
-    Promise.all([
-      page.waitForNavigation({ waitUntil: 'networkidle', timeout: 30000 }),
-      nextButton.dispatchEvent('click')
-    ])
-  ]);
-} catch (error) {
-  const currentUrl = page.url();
-  if (currentUrl === previousUrl) {
-    console.log("Previous URL same as current URL. Navigation failed.");
-  }
-}
+const MAX_NAVIGATION_ATTEMPTS = 3;
+let navigationAttempt = 0;
+
+while (navigationAttempt < MAX_NAVIGATION_ATTEMPTS) {
+  try {
+    await Promise.race([
+      page.waitForNavigation({ waitUntil: 'networkidle', timeout: 30000 })
+        .catch(() => null), // Prevent rejection from breaking the race
+      nextButton.click()
+        .catch(() => nextButton.dispatchEvent('click'))
+    ]);
+    
+    const currentUrl = page.url();
+    if (currentUrl !== previousUrl) {
+      break; // Navigation successful
+    }
+    
+    navigationAttempt++;
+    await page.waitForTimeout(1000 * navigationAttempt); // Exponential backoff
+  } catch (error) {
+    console.error(`Navigation attempt ${navigationAttempt + 1} failed:`, error);
+    navigationAttempt++;
+  }
+}
+
+if (navigationAttempt === MAX_NAVIGATION_ATTEMPTS) {
+  console.error('Max navigation attempts reached. Stopping pagination.');
+  return allResults;
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// const nextButton = await page.$(config.pagination.selector);
const nextButton = await page.$(workingSelector);
if (!nextButton) {
return allResults; // No more pages to scrape
}
await Promise.all([
nextButton.dispatchEvent('click'),
page.waitForNavigation({ waitUntil: 'networkidle' })
]);
const selectorIndex = availableSelectors.indexOf(workingSelector!);
availableSelectors = availableSelectors.slice(selectorIndex);
// await Promise.all([
// nextButton.dispatchEvent('click'),
// page.waitForNavigation({ waitUntil: 'networkidle' })
// ]);
const previousUrl = page.url();
visitedUrls.push(previousUrl);
try {
// Try both click methods simultaneously
await Promise.race([
Promise.all([
page.waitForNavigation({ waitUntil: 'networkidle', timeout: 30000 }),
nextButton.click()
]),
Promise.all([
page.waitForNavigation({ waitUntil: 'networkidle', timeout: 30000 }),
nextButton.dispatchEvent('click')
])
]);
} catch (error) {
// Verify if navigation actually succeeded
const currentUrl = page.url();
if (currentUrl === previousUrl) {
console.log("Previous URL same as current URL. Navigation failed.");
}
}
const currentUrl = page.url();
if (visitedUrls.includes(currentUrl)) {
console.log(`Detected navigation to a previously visited URL: ${currentUrl}`);
// Extract the current page number from the URL
const match = currentUrl.match(/\d+/);
if (match) {
const currentNumber = match[0];
// Use visitedUrls.length + 1 as the next page number
const nextNumber = visitedUrls.length + 1;
// Create new URL by replacing the current number with the next number
const nextUrl = currentUrl.replace(currentNumber, nextNumber.toString());
console.log(`Navigating to constructed URL: ${nextUrl}`);
// Navigate to the next page
await Promise.all([
page.waitForNavigation({ waitUntil: 'networkidle' }),
page.goto(nextUrl)
]);
}
}
// const nextButton = await page.$(config.pagination.selector);
const nextButton = await page.$(workingSelector);
if (!nextButton) {
return allResults; // No more pages to scrape
}
const selectorIndex = availableSelectors.indexOf(workingSelector!);
availableSelectors = availableSelectors.slice(selectorIndex);
// await Promise.all([
// nextButton.dispatchEvent('click'),
// page.waitForNavigation({ waitUntil: 'networkidle' })
// ]);
const previousUrl = page.url();
visitedUrls.push(previousUrl);
const MAX_NAVIGATION_ATTEMPTS = 3;
let navigationAttempt = 0;
while (navigationAttempt < MAX_NAVIGATION_ATTEMPTS) {
try {
await Promise.race([
page.waitForNavigation({ waitUntil: 'networkidle', timeout: 30000 })
.catch(() => null), // Prevent rejection from breaking the race
nextButton.click()
.catch(() => nextButton.dispatchEvent('click'))
]);
const currentUrl = page.url();
if (currentUrl !== previousUrl) {
break; // Navigation successful
}
navigationAttempt++;
await page.waitForTimeout(1000 * navigationAttempt); // Exponential backoff
} catch (error) {
console.error(`Navigation attempt ${navigationAttempt + 1} failed:`, error);
navigationAttempt++;
}
}
if (navigationAttempt === MAX_NAVIGATION_ATTEMPTS) {
console.error('Max navigation attempts reached. Stopping pagination.');
return allResults;
}
const currentUrl = page.url();
if (visitedUrls.includes(currentUrl)) {
console.log(`Detected navigation to a previously visited URL: ${currentUrl}`);
// Extract the current page number from the URL
const match = currentUrl.match(/\d+/);
if (match) {
const currentNumber = match[0];
// Use visitedUrls.length + 1 as the next page number
const nextNumber = visitedUrls.length + 1;
// Create new URL by replacing the current number with the next number
const nextUrl = currentUrl.replace(currentNumber, nextNumber.toString());
console.log(`Navigating to constructed URL: ${nextUrl}`);
// Navigate to the next page
await Promise.all([
page.waitForNavigation({ waitUntil: 'networkidle' }),
page.goto(nextUrl)
]);
}
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 623-623: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 628-628: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 636-636: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 659-659: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

@amhsirak amhsirak merged commit 070bc63 into develop Jan 13, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Type: Feature New features
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants