You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

网页控制台提取代金券代码求助:批量获取分页HTML中的voucher codes

Solution to Batch Extract Voucher Codes via Browser Console

Hey there! I totally get how tedious it is to manually copy 1000 voucher codes page by page—what a huge waste of time when you’ve got actual email development work to focus on. Let’s fix this with some straightforward JavaScript you can run right in your browser’s DevTools console.

First: Understand the Issue with Your Previous Attempts

The problem with using document.getElementById("tblEVoucherName") is that IDs must be unique on a page, but your HTML has multiple <td> elements using the same tblEVoucherName ID. That’s why it only returns one element. Using getElementsByClassName('sorting_1') was on the right track, but you need to handle pagination to grab codes from all pages.


Step 1: Extract Codes from the Current Page (Test First!)

Run this script to grab all voucher codes from the page you’re currently viewing, and copy them directly to your clipboard (perfect for testing):

// Extract voucher codes from the current page
const currentPageCodes = Array.from(document.querySelectorAll('.sorting_1'))
  .map(cell => cell.textContent.trim())
  .filter(code => code.startsWith('bbv')); // Filter to only get valid voucher codes (matches your example format)

// Log results to console
console.log('Current page voucher codes:', currentPageCodes);

// Copy to clipboard for easy pasting into Excel
navigator.clipboard.writeText(currentPageCodes.join('\n')).then(() => {
  console.log('✅ Current page codes copied to clipboard!');
}).catch(err => {
  console.error('❌ Failed to copy to clipboard:', err);
  // Fallback: Print all codes to console so you can manually copy
  console.log('Codes to copy:\n', currentPageCodes.join('\n'));
});

Step 2: Auto-Paginate & Extract All 1000 Codes

This script will automatically cycle through all pages, extract codes, and copy the full list to your clipboard when done. Since you need 1000 codes (5 per page), we’ll target 200 total pages—adjust the totalPages value if needed.

// Batch extract all voucher codes with auto-pagination
let allVoucherCodes = [];
let currentPage = 1;
const totalPages = 200; // 1000 codes ÷ 5 per page = 200 pages (adjust if your page count differs)

async function extractPageAndNext() {
  // Wait for the page to fully load new content (adjust timeout if your site is slow)
  await new Promise(resolve => setTimeout(resolve, 800));

  // Extract codes from the current page
  const pageCodes = Array.from(document.querySelectorAll('.sorting_1'))
    .map(cell => cell.textContent.trim())
    .filter(code => code.startsWith('bbv'));

  // Add to our full list
  allVoucherCodes = [...allVoucherCodes, ...pageCodes];
  console.log(`📄 Extracted page ${currentPage} | Total codes collected: ${allVoucherCodes.length}`);

  // Move to next page if we haven't finished
  if (currentPage < totalPages) {
    currentPage++;
    // Find the next page button (matches your pagination HTML structure)
    const nextPageBtn = document.querySelector(`li.paginate_button a[data-dt-idx="${currentPage}"]`);
    
    if (nextPageBtn) {
      nextPageBtn.click();
      // Wait for the page to switch before extracting again
      setTimeout(extractPageAndNext, 1000);
    } else {
      console.error('⚠️ Could not find next page button—check selector or page count.');
      finishExtraction();
    }
  } else {
    finishExtraction();
  }
}

function finishExtraction() {
  console.log(`🎉 Extraction complete! Total codes: ${allVoucherCodes.length}`);
  
  // Copy all codes to clipboard
  navigator.clipboard.writeText(allVoucherCodes.join('\n')).then(() => {
    console.log('✅ All codes copied to clipboard—paste directly into Excel!');
  }).catch(err => {
    console.error('❌ Clipboard copy failed:', err);
    // Fallback: Print all codes to console
    console.log('Full list of codes:\n', allVoucherCodes.join('\n'));
  });
}

// Start the extraction process
extractPageAndNext();

Important Notes for Success

  1. Adjust Timeouts: If your site loads slowly, increase the setTimeout values (e.g., change 800 to 1500 milliseconds) to give pages time to render new codes.
  2. Check Pagination Selector: If the script can’t find the next page button, inspect your pagination HTML again. You might need to tweak the document.querySelector selector (e.g., if the button class is different).
  3. Browser Clipboard Permissions: Some browsers block clipboard access by default—if you get an error, just copy the full list printed in the console instead.

内容的提问来源于stack exchange,提问作者Duicug

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:25:19