Recetas de datos

Extraer datos de páginas web con Python

BeautifulSoup Scraper · apify/beautifulsoup-scraper

Para desarrolladoresCódigo abiertoAutomatización👤 1,133 usuarios★ 4.7 (8)

Recorre sitios web y extrae información de las páginas con código Python, ya sea siguiendo enlaces o desde una lista de direcciones.

Para qué te sirve

  • Extraer datos de páginas sencillas
  • Recorrer un sitio completo
  • Armar bases de datos desde páginas web

Cómo empezar

  1. Entra a la herramienta con el botón "Probar gratis" y crea tu cuenta de Apify.
  2. Llena el formulario. Empieza con pocos resultados para gastar poco crédito.
  3. Dale "Start" y descarga el resultado en Excel o CSV desde "Storage".

Úsalo donde ya trabajas

Todo usa tu token de Apify. Cámbialo donde dice TU_TOKEN_DE_APIFY y no lo compartas. ¿Primera vez? Ve el curso gratis.

Pégalo en ChatGPT o Claude y llena tu objetivo.

Actúa como mi asistente de datos. Voy a usar el actor de Apify "apify/beautifulsoup-scraper" (extraer datos de páginas web con python).

Mi objetivo: [DESCRIBE QUÉ QUIERES LOGRAR, PARA QUÉ NEGOCIO Y EN QUÉ CIUDAD O NICHO]

1. Hazme máximo 3 preguntas si te falta algo para configurarlo.
2. Dame el JSON de input para pegar en Apify, empezando con pocos resultados para gastar poco crédito.
3. Dime qué columnas del resultado me van a importar y cuáles puedo ignorar.
4. Cuando te pase el CSV, sácame:
   - Extraer datos de páginas sencillas
   - Recorrer un sitio completo
   - Armar bases de datos desde páginas web
   Y entrégame una tabla con los 10 mejores casos y por qué.

No inventes datos: si algo no viene en el CSV, dímelo.

Copia, abre un workflow en n8n y pega con Ctrl+V. Lección de n8n.

{
  "name": "Extraer datos de páginas web con Python",
  "nodes": [
    {
      "parameters": {},
      "name": "Inicio",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        0
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.apify.com/v2/acts/apify~beautifulsoup-scraper/run-sync-get-dataset-items",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer TU_TOKEN_DE_APIFY"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "{\n  \"startUrls\": [\n    {\n      \"url\": \"https://crawlee.dev\"\n    }\n  ],\n  \"maxCrawlingDepth\": 1,\n  \"requestTimeout\": 10,\n  \"linkSelector\": \"a[href]\",\n  \"linkPatterns\": [\n    \".*crawlee\\\\.dev.*\"\n  ],\n  \"pageFunction\": \"from typing import Any\\nfrom crawlee.crawlers import BeautifulSoupCrawlingContext\\n\\n# See what fields the context object provides:\\n# https://crawlee.dev/python/api/class/BeautifulSoupCrawlingContext\\ndef page_function(context: BeautifulSoupCrawlingContext) -> Any:\\n    url = context.request.url\\n    title = context.soup.title.string if context.soup.title else None\\n    return {'url': url, 'title': title}\\n\",\n  \"soupFeatures\": \"html.parser\",\n  \"proxyConfiguration\": {\n    \"useApifyProxy\": true\n  }\n}",
        "options": {
          "timeout": 300000
        }
      },
      "name": "Apify",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        260,
        0
      ]
    }
  ],
  "connections": {
    "Inicio": {
      "main": [
        [
          {
            "node": "Apify",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
  1. Crea un escenario nuevo y agrega el módulo HTTP → "Make a request".
  2. URL: https://api.apify.com/v2/acts/apify~beautifulsoup-scraper/run-sync-get-dataset-items
  3. Method: POST.
  4. Headers: Authorization = Bearer TU_TOKEN_DE_APIFY
  5. Body type: Raw, Content type: JSON (application/json). En Request content pega el input de abajo.
  6. Marca "Parse response" para que cada resultado salga como dato y puedas mandarlo a Google Sheets con un Iterator.

Lección de Make

// npm install apify-client
import { ApifyClient } from 'apify-client';

const client = new ApifyClient({ token: process.env.APIFY_TOKEN });

const input = {
  "startUrls": [
    {
      "url": "https://crawlee.dev"
    }
  ],
  "maxCrawlingDepth": 1,
  "requestTimeout": 10,
  "linkSelector": "a[href]",
  "linkPatterns": [
    ".*crawlee\\.dev.*"
  ],
  "pageFunction": "from typing import Any\nfrom crawlee.crawlers import BeautifulSoupCrawlingContext\n\n# See what fields the context object provides:\n# https://crawlee.dev/python/api/class/BeautifulSoupCrawlingContext\ndef page_function(context: BeautifulSoupCrawlingContext) -> Any:\n    url = context.request.url\n    title = context.soup.title.string if context.soup.title else None\n    return {'url': url, 'title': title}\n",
  "soupFeatures": "html.parser",
  "proxyConfiguration": {
    "useApifyProxy": true
  }
};

const run = await client.actor('apify/beautifulsoup-scraper').call(input);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
console.log(items.length, 'resultados');
console.log(items[0]);
# pip install apify-client
import os
from apify_client import ApifyClient

client = ApifyClient(os.environ["APIFY_TOKEN"])

run_input = {
  "startUrls": [
    {
      "url": "https://crawlee.dev"
    }
  ],
  "maxCrawlingDepth": 1,
  "requestTimeout": 10,
  "linkSelector": "a[href]",
  "linkPatterns": [
    ".*crawlee\\.dev.*"
  ],
  "pageFunction": "from typing import Any\nfrom crawlee.crawlers import BeautifulSoupCrawlingContext\n\n# See what fields the context object provides:\n# https://crawlee.dev/python/api/class/BeautifulSoupCrawlingContext\ndef page_function(context: BeautifulSoupCrawlingContext) -> Any:\n    url = context.request.url\n    title = context.soup.title.string if context.soup.title else None\n    return {'url': url, 'title': title}\n",
  "soupFeatures": "html.parser",
  "proxyConfiguration": {
    "useApifyProxy": true
  }
}

run = client.actor("apify/beautifulsoup-scraper").call(run_input=run_input)
items = list(client.dataset(run["defaultDatasetId"]).iterate_items())
print(len(items), "resultados")
print(items[0] if items else "sin resultados")
curl -X POST "https://api.apify.com/v2/acts/apify~beautifulsoup-scraper/run-sync-get-dataset-items" \
  -H "Authorization: Bearer TU_TOKEN_DE_APIFY" \
  -H "Content-Type: application/json" \
  -d '{"startUrls":[{"url":"https://crawlee.dev"}],"maxCrawlingDepth":1,"requestTimeout":10,"linkSelector":"a[href]","linkPatterns":[".*crawlee\\.dev.*"],"pageFunction":"from typing import Any\nfrom crawlee.crawlers import BeautifulSoupCrawlingContext\n\n# See what fields the context object provides:\n# https://crawlee.dev/python/api/class/BeautifulSoupCrawlingContext\ndef page_function(context: BeautifulSoupCrawlingContext) -> Any:\n    url = context.request.url\n    title = context.soup.title.string if context.soup.title else None\n    return {'url': url, 'title': title}\n","soupFeatures":"html.parser","proxyConfiguration":{"useApifyProxy":true}}'

Parecidos en Para desarrolladores