Find the wanted form element within the given response.
(
response: TextResponse,
formname: str | None,
formid: str | None,
formnumber: int,
formxpath: str | None,
)
| 122 | |
| 123 | |
| 124 | def _get_form( |
| 125 | response: TextResponse, |
| 126 | formname: str | None, |
| 127 | formid: str | None, |
| 128 | formnumber: int, |
| 129 | formxpath: str | None, |
| 130 | ) -> FormElement: |
| 131 | """Find the wanted form element within the given response.""" |
| 132 | root = response.selector.root |
| 133 | forms = root.xpath("//form") |
| 134 | if not forms: |
| 135 | raise ValueError(f"No <form> element found in {response}") |
| 136 | |
| 137 | if formname is not None: |
| 138 | f = root.xpath(f'//form[@name="{formname}"]') |
| 139 | if f: |
| 140 | return cast("FormElement", f[0]) |
| 141 | |
| 142 | if formid is not None: |
| 143 | f = root.xpath(f'//form[@id="{formid}"]') |
| 144 | if f: |
| 145 | return cast("FormElement", f[0]) |
| 146 | |
| 147 | # Get form element from xpath, if not found, go up |
| 148 | if formxpath is not None: |
| 149 | nodes = root.xpath(formxpath) |
| 150 | if nodes: |
| 151 | el = nodes[0] |
| 152 | while True: |
| 153 | if el.tag == "form": |
| 154 | return cast("FormElement", el) |
| 155 | el = el.getparent() |
| 156 | if el is None: |
| 157 | break |
| 158 | raise ValueError(f"No <form> element found with {formxpath}") |
| 159 | |
| 160 | # If we get here, it means that either formname was None or invalid |
| 161 | try: |
| 162 | form = forms[formnumber] |
| 163 | except IndexError: |
| 164 | raise IndexError(f"Form number {formnumber} not found in {response}") from None |
| 165 | return cast("FormElement", form) |
| 166 | |
| 167 | |
| 168 | def _get_inputs( |