MechanicalSoup Documentation

repository·main·Indexed 26 days ago

https://github.com/mechanicalsoup/mechanicalsoup

A Python library for automating interactions with websites, providing a high-level API built on top of Requests and BeautifulSoup. It handles cookies, redirects, link following, and form submission. The library features a StatefulBrowser for maintaining session state and a Browser class for stateless requests. Note that MechanicalSoup does not support JavaScript.

Tokens
2.8K
Snippets
13
Records
30
Agent score
85%

What's inside MechanicalSoup

  1. Automate website interaction with StatefulBrowser

    main

    MechanicalSoup is a Python library for automating website interaction. It uses Requests for HTTP sessions and BeautifulSoup for document navigation. It automatically handles cookies, follows redirects, and can submit forms, but it does not support JavaScript.

    A common pattern is to use mechanicalsoup.StatefulBrowser to maintain a session, open a URL, select a form, fill in fields, and submit it.

  2. Install MechanicalSoup from source

    main

    To install from a local clone of the repository (which installs the version in your current working directory), follow these steps:

    1. Clone the repository.
    2. Navigate into the directory.
    3. Run the setup script.
    git clone https://github.com/MechanicalSoup/MechanicalSoup.git
    cd MechanicalSoup
    python setup.py install
  3. Choose between Browser and StatefulBrowser

    main
    Use mechanicalsoup.StatefulBrowser for almost all use cases. It is a superset of mechanicalsoup.Browser that automatically manages the current URL and form state, whereas mechanicalsoup.Browser requires you to manually track and manipulate these variables.
  4. Resolve "No parser was explicitly specified" warning

    main

    To avoid warnings and ensure consistent behavior across different systems, specify an HTML parser in the soup_config argument when initializing the browser.

    mechanicalsoup.StatefulBrowser(soup_config={'features': 'lxml', '...': '...'})
    
    # If lxml is not installed:
    mechanicalsoup.StatefulBrowser(soup_config={'features': 'parser.html', ...})
  5. Initialize a StatefulBrowser

    main

    To start a session that maintains state (like cookies and the current URL) across multiple requests, use the mechanicalsoup.StatefulBrowser class. You can customize the browser behavior (such as user-agent or HTML parser) via the __init__ method.

    import mechanicalsoup
    browser = mechanicalsoup.StatefulBrowser()