firecrawl-py


Namefirecrawl-py JSON
Version 1.2.4 PyPI version JSON
download
home_pagehttps://github.com/mendableai/firecrawl
SummaryPython SDK for Firecrawl API
upload_time2024-09-17 16:28:54
maintainerNone
docs_urlNone
authorMendable.ai
requires_python>=3.8
licenseGNU Affero General Public License v3 (AGPLv3)
keywords sdk api firecrawl
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Firecrawl Python SDK

The Firecrawl Python SDK is a library that allows you to easily scrape and crawl websites, and output the data in a format ready for use with language models (LLMs). It provides a simple and intuitive interface for interacting with the Firecrawl API.

## Installation

To install the Firecrawl Python SDK, you can use pip:

```bash
pip install firecrawl-py
```

## Usage

1. Get an API key from [firecrawl.dev](https://firecrawl.dev)
2. Set the API key as an environment variable named `FIRECRAWL_API_KEY` or pass it as a parameter to the `FirecrawlApp` class.

Here's an example of how to use the SDK:

```python
from firecrawl.firecrawl import FirecrawlApp

app = FirecrawlApp(api_key="fc-YOUR_API_KEY")

# Scrape a website:
scrape_status = app.scrape_url(
  'https://firecrawl.dev', 
  params={'formats': ['markdown', 'html']}
)
print(scrape_status)

# Crawl a website:
crawl_status = app.crawl_url(
  'https://firecrawl.dev', 
  params={
    'limit': 100, 
    'scrapeOptions': {'formats': ['markdown', 'html']}
  }, 
  wait_until_done=True, 
  poll_interval=30
)
print(crawl_status)
```

### Scraping a URL

To scrape a single URL, use the `scrape_url` method. It takes the URL as a parameter and returns the scraped data as a dictionary.

```python
url = 'https://example.com'
scraped_data = app.scrape_url(url)
```

### Extracting structured data from a URL

With LLM extraction, you can easily extract structured data from any URL. We support pydantic schemas to make it easier for you too. Here is how you to use it:

```python
class ArticleSchema(BaseModel):
    title: str
    points: int
    by: str
    commentsURL: str

class TopArticlesSchema(BaseModel):
    top: List[ArticleSchema] = Field(..., max_items=5, description="Top 5 stories")

data = app.scrape_url('https://news.ycombinator.com', {
    'extractorOptions': {
        'extractionSchema': TopArticlesSchema.model_json_schema(),
        'mode': 'llm-extraction'
    },
    'pageOptions':{
        'onlyMainContent': True
    }
})
print(data["llm_extraction"])
```

### Crawling a Website

To crawl a website, use the `crawl_url` method. It takes the starting URL and optional parameters as arguments. The `params` argument allows you to specify additional options for the crawl job, such as the maximum number of pages to crawl, allowed domains, and the output format.

```python
idempotency_key = str(uuid.uuid4()) # optional idempotency key
crawl_result = app.crawl_url('firecrawl.dev', {'excludePaths': ['blog/*']}, 2, idempotency_key)
print(crawl_result)
```

### Asynchronous Crawl a Website

To crawl a website asynchronously, use the `async_crawl_url` method. It takes the starting URL and optional parameters as arguments. The `params` argument allows you to specify additional options for the crawl job, such as the maximum number of pages to crawl, allowed domains, and the output format.

```python
crawl_result = app.async_crawl_url('firecrawl.dev', {'excludePaths': ['blog/*']}, "")
print(crawl_result)
```

### Checking Crawl Status

To check the status of a crawl job, use the `check_crawl_status` method. It takes the job ID as a parameter and returns the current status of the crawl job.

```python
id = crawl_result['id']
status = app.check_crawl_status(id)
```

### Map a Website

Use `map_url` to generate a list of URLs from a website. The `params` argument let you customize the mapping process, including options to exclude subdomains or to utilize the sitemap.

```python
# Map a website:
map_result = app.map_url('https://example.com')
print(map_result)
```

### Crawl a website with WebSockets

To crawl a website with WebSockets, use the `crawl_url_and_watch` method. It takes the starting URL and optional parameters as arguments. The `params` argument allows you to specify additional options for the crawl job, such as the maximum number of pages to crawl, allowed domains, and the output format.

```python
# inside an async function...
nest_asyncio.apply()

# Define event handlers
def on_document(detail):
    print("DOC", detail)

def on_error(detail):
    print("ERR", detail['error'])

def on_done(detail):
    print("DONE", detail['status'])

    # Function to start the crawl and watch process
async def start_crawl_and_watch():
    # Initiate the crawl job and get the watcher
    watcher = app.crawl_url_and_watch('firecrawl.dev', { 'excludePaths': ['blog/*'], 'limit': 5 })

    # Add event listeners
    watcher.add_event_listener("document", on_document)
    watcher.add_event_listener("error", on_error)
    watcher.add_event_listener("done", on_done)

    # Start the watcher
    await watcher.connect()

# Run the event loop
await start_crawl_and_watch()
```

## Error Handling

The SDK handles errors returned by the Firecrawl API and raises appropriate exceptions. If an error occurs during a request, an exception will be raised with a descriptive error message.

## Running the Tests with Pytest

To ensure the functionality of the Firecrawl Python SDK, we have included end-to-end tests using `pytest`. These tests cover various aspects of the SDK, including URL scraping, web searching, and website crawling.

### Running the Tests

To run the tests, execute the following commands:

Install pytest:

```bash
pip install pytest
```

Run:

```bash
pytest firecrawl/__tests__/e2e_withAuth/test.py
```

## Contributing

Contributions to the Firecrawl Python SDK are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request on the GitHub repository.

## License

The Firecrawl Python SDK is licensed under the MIT License. This means you are free to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the SDK, subject to the following conditions:

- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Please note that while this SDK is MIT licensed, it is part of a larger project which may be under different licensing terms. Always refer to the license information in the root directory of the main project for overall licensing details.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/mendableai/firecrawl",
    "name": "firecrawl-py",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "\"Mendable.ai\" <nick@mendable.ai>",
    "keywords": "SDK, API, firecrawl",
    "author": "Mendable.ai",
    "author_email": "\"Mendable.ai\" <nick@mendable.ai>",
    "download_url": "https://files.pythonhosted.org/packages/57/61/97e6d879156f9c4a30f86eab894c46387948f9455e57820cd0b2c483f8e5/firecrawl_py-1.2.4.tar.gz",
    "platform": null,
    "description": "# Firecrawl Python SDK\n\nThe Firecrawl Python SDK is a library that allows you to easily scrape and crawl websites, and output the data in a format ready for use with language models (LLMs). It provides a simple and intuitive interface for interacting with the Firecrawl API.\n\n## Installation\n\nTo install the Firecrawl Python SDK, you can use pip:\n\n```bash\npip install firecrawl-py\n```\n\n## Usage\n\n1. Get an API key from [firecrawl.dev](https://firecrawl.dev)\n2. Set the API key as an environment variable named `FIRECRAWL_API_KEY` or pass it as a parameter to the `FirecrawlApp` class.\n\nHere's an example of how to use the SDK:\n\n```python\nfrom firecrawl.firecrawl import FirecrawlApp\n\napp = FirecrawlApp(api_key=\"fc-YOUR_API_KEY\")\n\n# Scrape a website:\nscrape_status = app.scrape_url(\n  'https://firecrawl.dev', \n  params={'formats': ['markdown', 'html']}\n)\nprint(scrape_status)\n\n# Crawl a website:\ncrawl_status = app.crawl_url(\n  'https://firecrawl.dev', \n  params={\n    'limit': 100, \n    'scrapeOptions': {'formats': ['markdown', 'html']}\n  }, \n  wait_until_done=True, \n  poll_interval=30\n)\nprint(crawl_status)\n```\n\n### Scraping a URL\n\nTo scrape a single URL, use the `scrape_url` method. It takes the URL as a parameter and returns the scraped data as a dictionary.\n\n```python\nurl = 'https://example.com'\nscraped_data = app.scrape_url(url)\n```\n\n### Extracting structured data from a URL\n\nWith LLM extraction, you can easily extract structured data from any URL. We support pydantic schemas to make it easier for you too. Here is how you to use it:\n\n```python\nclass ArticleSchema(BaseModel):\n    title: str\n    points: int\n    by: str\n    commentsURL: str\n\nclass TopArticlesSchema(BaseModel):\n    top: List[ArticleSchema] = Field(..., max_items=5, description=\"Top 5 stories\")\n\ndata = app.scrape_url('https://news.ycombinator.com', {\n    'extractorOptions': {\n        'extractionSchema': TopArticlesSchema.model_json_schema(),\n        'mode': 'llm-extraction'\n    },\n    'pageOptions':{\n        'onlyMainContent': True\n    }\n})\nprint(data[\"llm_extraction\"])\n```\n\n### Crawling a Website\n\nTo crawl a website, use the `crawl_url` method. It takes the starting URL and optional parameters as arguments. The `params` argument allows you to specify additional options for the crawl job, such as the maximum number of pages to crawl, allowed domains, and the output format.\n\n```python\nidempotency_key = str(uuid.uuid4()) # optional idempotency key\ncrawl_result = app.crawl_url('firecrawl.dev', {'excludePaths': ['blog/*']}, 2, idempotency_key)\nprint(crawl_result)\n```\n\n### Asynchronous Crawl a Website\n\nTo crawl a website asynchronously, use the `async_crawl_url` method. It takes the starting URL and optional parameters as arguments. The `params` argument allows you to specify additional options for the crawl job, such as the maximum number of pages to crawl, allowed domains, and the output format.\n\n```python\ncrawl_result = app.async_crawl_url('firecrawl.dev', {'excludePaths': ['blog/*']}, \"\")\nprint(crawl_result)\n```\n\n### Checking Crawl Status\n\nTo check the status of a crawl job, use the `check_crawl_status` method. It takes the job ID as a parameter and returns the current status of the crawl job.\n\n```python\nid = crawl_result['id']\nstatus = app.check_crawl_status(id)\n```\n\n### Map a Website\n\nUse `map_url` to generate a list of URLs from a website. The `params` argument let you customize the mapping process, including options to exclude subdomains or to utilize the sitemap.\n\n```python\n# Map a website:\nmap_result = app.map_url('https://example.com')\nprint(map_result)\n```\n\n### Crawl a website with WebSockets\n\nTo crawl a website with WebSockets, use the `crawl_url_and_watch` method. It takes the starting URL and optional parameters as arguments. The `params` argument allows you to specify additional options for the crawl job, such as the maximum number of pages to crawl, allowed domains, and the output format.\n\n```python\n# inside an async function...\nnest_asyncio.apply()\n\n# Define event handlers\ndef on_document(detail):\n    print(\"DOC\", detail)\n\ndef on_error(detail):\n    print(\"ERR\", detail['error'])\n\ndef on_done(detail):\n    print(\"DONE\", detail['status'])\n\n    # Function to start the crawl and watch process\nasync def start_crawl_and_watch():\n    # Initiate the crawl job and get the watcher\n    watcher = app.crawl_url_and_watch('firecrawl.dev', { 'excludePaths': ['blog/*'], 'limit': 5 })\n\n    # Add event listeners\n    watcher.add_event_listener(\"document\", on_document)\n    watcher.add_event_listener(\"error\", on_error)\n    watcher.add_event_listener(\"done\", on_done)\n\n    # Start the watcher\n    await watcher.connect()\n\n# Run the event loop\nawait start_crawl_and_watch()\n```\n\n## Error Handling\n\nThe SDK handles errors returned by the Firecrawl API and raises appropriate exceptions. If an error occurs during a request, an exception will be raised with a descriptive error message.\n\n## Running the Tests with Pytest\n\nTo ensure the functionality of the Firecrawl Python SDK, we have included end-to-end tests using `pytest`. These tests cover various aspects of the SDK, including URL scraping, web searching, and website crawling.\n\n### Running the Tests\n\nTo run the tests, execute the following commands:\n\nInstall pytest:\n\n```bash\npip install pytest\n```\n\nRun:\n\n```bash\npytest firecrawl/__tests__/e2e_withAuth/test.py\n```\n\n## Contributing\n\nContributions to the Firecrawl Python SDK are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request on the GitHub repository.\n\n## License\n\nThe Firecrawl Python SDK is licensed under the MIT License. This means you are free to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the SDK, subject to the following conditions:\n\n- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nPlease note that while this SDK is MIT licensed, it is part of a larger project which may be under different licensing terms. Always refer to the license information in the root directory of the main project for overall licensing details.\n",
    "bugtrack_url": null,
    "license": "GNU Affero General Public License v3 (AGPLv3)",
    "summary": "Python SDK for Firecrawl API",
    "version": "1.2.4",
    "project_urls": {
        "Documentation": "https://docs.firecrawl.dev",
        "Homepage": "https://github.com/mendableai/firecrawl",
        "Source": "https://github.com/mendableai/firecrawl",
        "Tracker": "https://github.com/mendableai/firecrawl/issues"
    },
    "split_keywords": [
        "sdk",
        " api",
        " firecrawl"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "07df6acbd1dc884086770856e39a4d128ee54007653ef19d23d95ea31433cfc6",
                "md5": "3a5f950bac4eb5fb2742d8d2cdd117ec",
                "sha256": "0464992f354f4f7830dc29433dacad127a9cd73e331601c719f811df70bace58"
            },
            "downloads": -1,
            "filename": "firecrawl_py-1.2.4-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "3a5f950bac4eb5fb2742d8d2cdd117ec",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 15181,
            "upload_time": "2024-09-17T16:28:53",
            "upload_time_iso_8601": "2024-09-17T16:28:53.243187Z",
            "url": "https://files.pythonhosted.org/packages/07/df/6acbd1dc884086770856e39a4d128ee54007653ef19d23d95ea31433cfc6/firecrawl_py-1.2.4-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "576197e6d879156f9c4a30f86eab894c46387948f9455e57820cd0b2c483f8e5",
                "md5": "d007e417bfd8c77cc684427e02432766",
                "sha256": "bff3cfbce725739f6d7d7f8975b43be392f17c844f601485f19c2ddcf2b4f8de"
            },
            "downloads": -1,
            "filename": "firecrawl_py-1.2.4.tar.gz",
            "has_sig": false,
            "md5_digest": "d007e417bfd8c77cc684427e02432766",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 16031,
            "upload_time": "2024-09-17T16:28:54",
            "upload_time_iso_8601": "2024-09-17T16:28:54.472498Z",
            "url": "https://files.pythonhosted.org/packages/57/61/97e6d879156f9c4a30f86eab894c46387948f9455e57820cd0b2c483f8e5/firecrawl_py-1.2.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-09-17 16:28:54",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "mendableai",
    "github_project": "firecrawl",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "firecrawl-py"
}
        
Elapsed time: 2.69942s