### Install MechanicalSoup from source
Source: https://mechanicalsoup.readthedocs.io/en/stable/introduction.html
Clone the repository and run the setup script to install the version located in the current working directory.
```bash
git clone https://github.com/MechanicalSoup/MechanicalSoup.git
cd MechanicalSoup
python setup.py install
```
--------------------------------
### Install MechanicalSoup development version
Source: https://mechanicalsoup.readthedocs.io/en/stable/introduction.html
Use this command to install the latest development version directly from the GitHub repository.
```bash
pip install git+https://github.com/MechanicalSoup/MechanicalSoup
```
--------------------------------
### Complete StatefulBrowser example
Source: https://mechanicalsoup.readthedocs.io/en/stable/tutorial.html
Demonstrates navigating to a page, filling a form, and submitting it using StatefulBrowser.
```python
import mechanicalsoup
browser = mechanicalsoup.StatefulBrowser()
browser.open("http://httpbin.org/")
print(browser.url)
browser.follow_link("forms")
print(browser.url)
print(browser.page)
browser.select_form('form[action="/post"]')
browser["custname"] = "Me"
browser["custtel"] = "00 00 0001"
browser["custemail"] = "nobody@example.com"
browser["size"] = "medium"
browser["topping"] = "onion"
browser["topping"] = ("bacon", "cheese")
browser["comments"] = "This pizza looks really good :-)"
# Uncomment to launch a real web browser on the current page.
# browser.launch_browser()
# Uncomment to display a summary of the filled-in form
# browser.form.print_summary()
response = browser.submit_selected()
print(response.text)
```
--------------------------------
### Install MechanicalSoup dependencies
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/ChangeLog.rst.txt
Use pip to install the required dependencies for the project and its test suite.
```bash
pip install -r requirements.txt -r tests/requirements.txt
```
--------------------------------
### GET /get
Source: https://mechanicalsoup.readthedocs.io/en/stable/mechanicalsoup.html
Performs a GET request and returns a response with a soup object.
```APIDOC
## GET /get
### Description
Straightforward wrapper around requests.Session.get.
### Method
GET
### Response
#### Success Response (200)
- **response** (requests.Response) - A requests.Response object with a _soup_ attribute added.
```
--------------------------------
### GET /open
Source: https://mechanicalsoup.readthedocs.io/en/stable/mechanicalsoup.html
Opens a URL and updates the browser state.
```APIDOC
## GET /open
### Description
Opens the specified URL and stores the browser's state within the object.
### Method
GET
### Endpoint
open(url, *args, **kwargs)
### Parameters
#### Path Parameters
- **url** (string) - Required - The URL to navigate to.
### Response
- **Response** (requests.Response) - The response object from the request.
```
--------------------------------
### Install MechanicalSoup via pip
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/introduction.rst.txt
Use these commands to install the latest released or development version of MechanicalSoup.
```bash
pip install MechanicalSoup
```
```bash
pip install git+https://github.com/MechanicalSoup/MechanicalSoup
```
--------------------------------
### Install MechanicalSoup via pip
Source: https://mechanicalsoup.readthedocs.io/en/stable/introduction.html
Use this command to install the latest stable version of MechanicalSoup from the Python Package Index.
```bash
pip install MechanicalSoup
```
--------------------------------
### Get Current URL
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/tutorial.rst.txt
Retrieves the URL of the currently opened webpage.
```python
>>> browser.url
'http://httpbin.org/'
```
--------------------------------
### GET /download_link
Source: https://mechanicalsoup.readthedocs.io/en/stable/mechanicalsoup.html
Downloads the contents of a link to a local file without changing browser state.
```APIDOC
## GET /download_link
### Description
Downloads the contents of a link to a specified file path.
### Method
GET
### Endpoint
download_link(link=None, file=None, **kwargs)
### Parameters
#### Query Parameters
- **link** (Tag/string) - Optional - The link to download.
- **file** (string) - Required - Filesystem path where the contents will be saved.
### Response
- **Response** (requests.Response) - The response object.
```
--------------------------------
### Initialize StatefulBrowser
Source: https://mechanicalsoup.readthedocs.io/en/stable/mechanicalsoup.html
Instantiate StatefulBrowser with custom configurations for parsing, error handling, and user agent. Use this to begin a web scraping session.
```python
browser = mechanicalsoup.StatefulBrowser(
soup_config={'features': 'lxml'},
raise_on_404=True,
user_agent='MyBot/0.1: mysite.example.com/bot_info',
)
browser.open(url)
```
--------------------------------
### Create a StatefulBrowser Instance
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/tutorial.rst.txt
Initializes a StatefulBrowser object for web scraping. Customize browser behavior using parameters in StatefulBrowser.__init__.
```python
>>> import mechanicalsoup
>>> browser = mechanicalsoup.StatefulBrowser()
```
--------------------------------
### Login to GitHub with Browser class
Source: https://mechanicalsoup.readthedocs.io/en/stable/tutorial.html
Demonstrates manual state management using the plain Browser class for GitHub login.
```python
"""Example app to login to GitHub, using the plain Browser class.
See example.py for an example using the more advanced StatefulBrowser."""
import argparse
import mechanicalsoup
parser = argparse.ArgumentParser(description="Login to GitHub.")
parser.add_argument("username")
parser.add_argument("password")
args = parser.parse_args()
browser = mechanicalsoup.Browser(soup_config={'features': 'lxml'})
# request github login page. the result is a requests.Response object
# http://docs.python-requests.org/en/latest/user/quickstart/#response-content
login_page = browser.get("https://github.com/login")
# similar to assert login_page.ok but with full status code in case of
# failure.
login_page.raise_for_status()
# login_page.soup is a BeautifulSoup object
# http://www.crummy.com/software/BeautifulSoup/bs4/doc/#beautifulsoup
```
--------------------------------
### Launch Browser with Form Changes
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/tutorial.rst.txt
Opens the current page in a real web browser, reflecting any modifications made to the form fields. This creates a temporary file for display.
```python
>>> browser.launch_browser()
```
--------------------------------
### Login to GitHub with StatefulBrowser
Source: https://mechanicalsoup.readthedocs.io/en/stable/tutorial.html
Automates the login process for GitHub using StatefulBrowser. Note that this will not work with 2FA enabled.
```python
"""Example app to login to GitHub using the StatefulBrowser class.
NOTE: This example will not work if the user has 2FA enabled."""
import argparse
from getpass import getpass
import mechanicalsoup
parser = argparse.ArgumentParser(description="Login to GitHub.")
parser.add_argument("username")
args = parser.parse_args()
args.password = getpass("Please enter your GitHub password: ")
browser = mechanicalsoup.StatefulBrowser(
soup_config={'features': 'lxml'},
raise_on_404=True,
user_agent='MyBot/0.1: mysite.example.com/bot_info',
)
# Uncomment for a more verbose output:
# browser.set_verbose(2)
browser.open("https://github.com")
browser.follow_link("login")
browser.select_form('#login form')
browser["login"] = args.username
browser["password"] = args.password
resp = browser.submit_selected()
# Uncomment to launch a web browser on the current page:
# browser.launch_browser()
# verify we are now logged in
page = browser.page
messages = page.find("div", class_="flash-messages")
if messages:
print(messages.text)
assert page.select(".logout-form")
print(page.title.text)
# verify we remain logged in (thanks to cookies) as we browse the rest of
# the site
page3 = browser.open("https://github.com/MechanicalSoup/MechanicalSoup")
assert page3.soup.select(".logout-form")
```
--------------------------------
### POST /submit
Source: https://mechanicalsoup.readthedocs.io/en/stable/mechanicalsoup.html
Submits a form using the Browser instance.
```APIDOC
## POST /submit
### Description
Prepares and sends a form request using the provided form object.
### Method
POST
### Parameters
#### Request Body
- **form** (object) - Required - The filled-out form.
- **url** (string) - Optional - URL of the page the form is on.
- **kwargs** (dict) - Optional - Arguments forwarded to requests.Session.request.
### Response
#### Success Response (200)
- **response** (requests.Response) - A requests.Response object with a _soup_ attribute added.
```
--------------------------------
### Print form summary
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/tutorial.rst.txt
Displays the current state and fields of the selected form.
```python
>>> browser.form.print_summary()
```
--------------------------------
### POST /post
Source: https://mechanicalsoup.readthedocs.io/en/stable/mechanicalsoup.html
Performs a POST request and returns a response with a soup object.
```APIDOC
## POST /post
### Description
Straightforward wrapper around requests.Session.post.
### Method
POST
### Response
#### Success Response (200)
- **response** (requests.Response) - A requests.Response object with a _soup_ attribute added.
```
--------------------------------
### Set Form Field Values
Source: https://mechanicalsoup.readthedocs.io/en/stable/mechanicalsoup.html
Demonstrates filling standard text fields and checkboxes using the set method.
```python
form.set("login", username)
form.set("password", password)
form.set("eula-checkbox", True)
```
--------------------------------
### Print form summary
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/ChangeLog.rst.txt
Display a summary of form fields and their current fill status.
```python
browser.get_current_form().print_summary()
```
--------------------------------
### StatefulBrowser Class
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/mechanicalsoup.rst.txt
Documentation for the StatefulBrowser class, which allows for stateful browsing through web pages.
```APIDOC
## StatefulBrowser Class
### Description
Provides functionality for stateful web browsing, maintaining cookies and other session information across requests.
### Members
- `__setitem__` (special member)
- Other members documented by `autoclass` directive.
```
--------------------------------
### Log in to GitHub with MechanicalSoup
Source: https://mechanicalsoup.readthedocs.io/en/stable/tutorial.html
Use this snippet to log into a website by selecting a form, providing credentials, and submitting it. Ensure the form and input names match the website's HTML structure. Cookies are automatically handled to maintain the session.
```python
import mechanicalsoup
# Assume 'browser' is an instance of mechanicalsoup.Browser
# and 'login_page' is a mechanicalsoup.Link object representing the login page.
# Also assume 'args' is an object with 'username' and 'password' attributes.
# we grab the login form
login_form = mechanicalsoup.Form(login_page.soup.select_one('#login form'))
# specify username and password
login_form.input({"login": args.username, "password": args.password})
# submit form
page2 = browser.submit(login_form, login_page.url)
# verify we are now logged in
messages = page2.soup.find("div", class_="flash-messages")
if messages:
print(messages.text)
assert page2.soup.select(".logout-form")
print(page2.soup.title.text)
# verify we remain logged in (thanks to cookies) as we browse the rest of
# the site
page3 = browser.get("https://github.com/MechanicalSoup/MechanicalSoup")
assert page3.soup.select(".logout-form")
```
--------------------------------
### Print Form Summary
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/tutorial.rst.txt
Displays a summary of the fields available in the currently selected form, including their names and types.
```python
>>> browser.form.print_summary()
```
--------------------------------
### StatefulBrowser usage
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/tutorial.rst.txt
Uses the StatefulBrowser class to maintain navigation state.
```python
.. literalinclude:: ../examples/example.py
:language: python
```
--------------------------------
### Browser usage
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/tutorial.rst.txt
Uses the Browser class for stateless navigation where the caller manages state.
```python
.. literalinclude:: ../examples/example_manual.py
:language: python
```
--------------------------------
### Specify HTML Parser in StatefulBrowser
Source: https://mechanicalsoup.readthedocs.io/en/stable/faq.html
When initializing StatefulBrowser, provide a soup_config dictionary to explicitly specify the HTML parser features. This prevents 'No parser was explicitly specified' warnings.
```python
mechanicalsoup.StatefulBrowser(soup_config={'features': 'lxml', '...': '...'})
```
```python
mechanicalsoup.StatefulBrowser(soup_config={'features': 'parser.html', ...})
```
--------------------------------
### Open a Webpage
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/tutorial.rst.txt
Opens a specified URL using the browser object. The return value is a requests.Response object containing page data and metadata.
```python
>>> browser.open("http://httpbin.org/")
```
--------------------------------
### Fill Form Fields with set_input
Source: https://mechanicalsoup.readthedocs.io/en/stable/mechanicalsoup.html
Populates multiple form fields simultaneously using a dictionary mapping names to values.
```python
form.set_input({"login": username, "password": password})
```
--------------------------------
### Exceptions
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/mechanicalsoup.rst.txt
Documentation for custom exceptions raised by the MechanicalSoup package.
```APIDOC
## Exceptions
### LinkNotFoundError
#### Description
Raised when a specified link cannot be found on the page.
### InvalidFormMethod
#### Description
Raised when an invalid HTTP method is used for a form submission.
```
--------------------------------
### Activate Requests Logging for Debugging
Source: https://mechanicalsoup.readthedocs.io/en/stable/faq.html
Enable detailed logging for the requests library to see HTTP status codes and redirect information. This provides more verbose output than MechanicalSoup's built-in logging.
```python
import requests
import logging
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
```
--------------------------------
### Browser Class
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/mechanicalsoup.rst.txt
Documentation for the Browser class, a simpler browser interface for navigating web pages.
```APIDOC
## Browser Class
### Description
A basic browser class for navigating and interacting with web pages.
### Members
- Members documented by `autoclass` directive.
```
--------------------------------
### Submit selected form
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/tutorial.rst.txt
Simulates a click on the submit button of the currently selected form.
```python
>>> response = browser.submit_selected()
```
--------------------------------
### Follow a Link by Text
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/tutorial.rst.txt
Navigates to a link on the current page whose text matches the provided regular expression. Updates the browser's current URL.
```python
>>> browser.follow_link("forms")
>>> browser.url
'http://httpbin.org/forms/post'
```
--------------------------------
### Update file upload syntax
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/ChangeLog.rst.txt
Files must now be opened explicitly using a file object instead of a string path to prevent arbitrary file access.
```python
browser["upload"] = "/path/to/file"
```
```python
browser["upload"] = open("/path/to/file", "rb")
```
--------------------------------
### MechanicalSoup StatefulBrowser Methods
Source: https://mechanicalsoup.readthedocs.io/en/stable/genindex.html
Methods for the StatefulBrowser class to manage navigation, link discovery, and form interaction.
```APIDOC
## GET /statefulbrowser/open
### Description
Opens a URL using the StatefulBrowser.
### Method
GET
## GET /statefulbrowser/follow_link
### Description
Follows a link found on the current page.
### Method
GET
## POST /statefulbrowser/submit_selected
### Description
Submits the currently selected form.
### Method
POST
```
--------------------------------
### POST /select_form
Source: https://mechanicalsoup.readthedocs.io/en/stable/mechanicalsoup.html
Selects a form on the current page for subsequent interactions.
```APIDOC
## POST /select_form
### Description
Selects a form in the current page using a CSS selector or a BeautifulSoup Tag object.
### Method
POST
### Endpoint
select_form(selector='form', nr=0)
### Parameters
#### Query Parameters
- **selector** (string/Tag) - Optional - CSS selector or Tag object to identify the form. Defaults to 'form'.
- **nr** (integer) - Optional - Zero-based index to select a specific form if multiple match. Defaults to 0.
```
--------------------------------
### Activate request logging
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/faq.rst.txt
Enables verbose logging for the underlying requests library to debug HTTP status codes and redirects.
```python
import requests
import logging
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
```
--------------------------------
### Create Text Input with Form.set
Source: https://mechanicalsoup.readthedocs.io/en/stable/ChangeLog.html
When `force=True` is used with `Form.set()`, it creates an `` element instead of an ``.
```python
Form.set(force=True)
```
--------------------------------
### Select Checkboxes
Source: https://mechanicalsoup.readthedocs.io/en/stable/tutorial.html
Check one or multiple boxes by assigning a string or a list of strings.
```python
>>> browser["topping"] = "bacon"
>>> browser["topping"] = ("bacon", "cheese")
```
--------------------------------
### Form Class
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/mechanicalsoup.rst.txt
Documentation for the Form class, used for interacting with HTML forms.
```APIDOC
## Form Class
### Description
Represents an HTML form, allowing for easy manipulation and submission of form data.
### Members
- `__setitem__` (special member)
- Other members documented by `autoclass` directive.
```
--------------------------------
### Form Class Overview
Source: https://mechanicalsoup.readthedocs.io/en/stable/mechanicalsoup.html
The Form class prepares HTML forms for submission. It handles input, select, and textarea elements, with methods for setting values based on element type.
```APIDOC
## Form Class
### Description
Build a fillable form. The Form class is responsible for preparing HTML forms for submission. It handles the following types of elements: input (text, checkbox, radio), select, and textarea.
### Parameters
- **form** (bs4.element.Tag) - A bs4.element.Tag corresponding to an HTML form element.
```
--------------------------------
### MechanicalSoup Browser Methods
Source: https://mechanicalsoup.readthedocs.io/en/stable/genindex.html
Core methods for the Browser class to perform HTTP requests and manage browser state.
```APIDOC
## GET /browser/get
### Description
Performs a GET request using the Browser instance.
### Method
GET
## POST /browser/post
### Description
Performs a POST request using the Browser instance.
### Method
POST
## PUT /browser/put
### Description
Performs a PUT request using the Browser instance.
### Method
PUT
## POST /browser/submit
### Description
Submits a form using the Browser instance.
### Method
POST
```
--------------------------------
### Upload File via Form
Source: https://mechanicalsoup.readthedocs.io/en/stable/mechanicalsoup.html
Uploads a local file by passing an open file object to the set method for an input of type file.
```python
form.set("tagname", open(path_to_local_file, "rb"))
```
--------------------------------
### Select a Form by CSS Selector
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/tutorial.rst.txt
Selects a form on the page using a CSS selector. If multiple forms exist, a more specific selector is needed. If only one form exists, it can be selected without arguments.
```python
>>> browser.select_form('form[action="/post"]')
```
--------------------------------
### Display response text
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/tutorial.rst.txt
Accesses the raw text content of the response object.
```python
>>> print(response.text)
{
"args": {},
"data": "",
"files": {},
"form": {
"comments": "This pizza looks really good :-)",
"custemail": "nobody@example.com",
"custname": "Me",
"custtel": "00 00 0001",
"delivery": "",
"size": "medium",
"topping": [
"bacon",
"cheese"
]
},
...
```
--------------------------------
### Set checkbox values
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/ChangeLog.rst.txt
Update checkbox states by providing a tuple of values to the browser instance.
```python
browser["name"] = ("val1", "val2")
```
--------------------------------
### Use StatefulBrowser with a 'with' statement
Source: https://mechanicalsoup.readthedocs.io/en/stable/faq.html
Employ the 'with' statement when using StatefulBrowser to ensure that the browser's close() method is automatically called upon exiting the block. This prevents potential 'ReferenceError: weakly-referenced object no longer exists' errors.
```python
def test_with():
with mechanicalsoup.StatefulBrowser() as browser:
browser.open(url)
# ...
# implicit call to browser.close() here.
```
--------------------------------
### Access Page Content
Source: https://mechanicalsoup.readthedocs.io/en/stable/_sources/tutorial.rst.txt
Retrieves the parsed HTML content of the current page as a BeautifulSoup object. Allows for navigation and manipulation of HTML tags.
```python
>>> browser.page
...