البرمجة

كيفية سكرابنج بيانات الجداول بواسطة Puppeteer

To scrape data from a website that uses JavaScript to load content, you can use a technique called “web scraping” along with a headless browser like Puppeteer in Node.js. Here’s a general approach to scraping data from the British Cycling event page you provided as an example:

  1. Install Puppeteer: If you haven’t already, install Puppeteer by running npm install puppeteer in your Node.js project directory.

  2. Write a script: Create a JavaScript file (e.g., scrape.js) with the following code:

    javascript
    const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.britishcycling.org.uk/events/details/141520/London-Dynamo-Summer-Road-Race-2016'); // Click the "View Entrants" button await page.click('.js-view-entrants'); // Wait for the table to load await page.waitForSelector('.entrants-table'); // Get the HTML content of the table const tableHTML = await page.$eval('.entrants-table', table => table.outerHTML); console.log(tableHTML); await browser.close(); })();

    This script uses Puppeteer to open the event page, click the “View Entrants” button, wait for the table to load, and then log the HTML content of the table to the console.

  3. Run the script: Run the script using Node.js by running node scrape.js in your terminal.

Keep in mind that scraping websites without permission may violate their terms of service, so make sure to check the website’s terms and conditions before proceeding.

المزيد من المعلومات

بالطبع! يمكننا توسيع المعلومات حول كيفية الحصول على بيانات الجدول بدقة أكبر. في السكربت السابق، قمنا بالضغط على زر “عرض المشتركين” وانتظرنا حتى تحميل الجدول. ومع ذلك، قد تحتاج أحيانًا إلى تحسين هذه العملية بإضافة بعض الخطوات الإضافية. هنا بعض النصائح لتحسين السكربت:

  1. التأكد من تحميل الصفحة بشكل كامل: قد تحتاج إلى استخدام page.waitForNavigation() بدلاً من page.waitForSelector() بعد النقر على الزر للتأكد من أن الصفحة قد تم تحميلها بشكل كامل قبل استخراج البيانات.

  2. التحقق من توافر البيانات: قد تحتاج إلى استخدام page.waitForSelector() للتأكد من تحميل الجدول بشكل كامل قبل استخراج بياناته.

  3. تحسين الأداء: للحصول على أداء أفضل، يمكنك استخدام page.evaluate() لتشغيل الكود JavaScript داخل صفحة الويب واستخراج البيانات مباشرةً دون الحاجة إلى تحديد عناصر HTML.

  4. تجنب الحظر: لتجنب حظر IP، يجب أن تكون عملية السكرابنج بطيئة ومتدرجة. يفضل أيضًا استخدام بروكسي لإخفاء عنوان IP الخاص بك.

  5. التعامل مع التحديثات والتغييرات: يجب أن تكون عملية السكرابنج قابلة للتكيف مع أي تغييرات في هيكل الصفحة، مثل تغييرات في CSS أو تغييرات في عناصر HTML.

هذه النصائح يمكن أن تساعد في تحسين عملية السكرابنج وجعلها أكثر فعالية وموثوقية.

زر الذهاب إلى الأعلى