=====
Usage
=====
:ref:`Given an HTML form
"""
>>> selector = Selector(body=html, base_url="https://example.com")
>>> form = selector.css("form")
You can use :func:`~form2request.form2request` to generate form submission
request data:
>>> from form2request import form2request
>>> request_data = form2request(form)
>>> request_data
Request(url='https://example.com?foo=bar', method='GET', headers=[], body=b'')
:func:`~form2request.form2request` does not make requests, but you can use its
output to build requests with any HTTP client software. It also provides
:ref:`conversion methods for common use cases `, e.g. for the
:doc:`requests ` library:
.. _requests-example:
>>> import requests
>>> request = request_data.to_requests()
>>> requests.send(request) # doctest: +SKIP
:func:`~form2request.form2request` supports :ref:`user-defined form data
`, :ref:`file uploads `, :ref:`choosing a specific submit button
(or none) `, and :ref:`overriding form attributes `.
.. _form:
Getting a form
==============
:func:`~form2request.form2request` requires an HTML form object. You can get
one using :doc:`parsel `, as :ref:`seen above `,
or you can use :doc:`lxml `:
.. _fromstring-example:
>>> from lxml.html import fromstring
>>> root = fromstring(html, base_url="https://example.com")
>>> form = root.xpath("//form")[0]
If you use a library or framework based on :doc:`parsel ` or
:doc:`lxml `, chances are they also let you get a form object. For
example, when using a :doc:`Scrapy ` response:
>>> from scrapy.http import TextResponse
>>> response = TextResponse("https://example.com", body=html)
>>> form = response.css("form")
Here are some examples of XPath expressions that can be useful to get a form
using parsel’s :meth:`Selector.xpath ` or
lxml’s :meth:`HtmlElement.xpath `:
- To find a form by one of its attributes, such as ``id`` or ``name``, use
``//form[@=""]``. For example, to find ``