We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[Bug] Incorrectly picked URL in `scrapy.http.FormRequest.from_response` when there is a `<base>` tag
## Issue Description

Incorrectly picked URL in `scrapy.http.FormRequest.from_response` when there is a `<base>` tag.
## How to Reproduce the Issue & Version Used

```
[pengyu@GLaDOS tmp]$ python2
Python 2.7.10 (default, Sep  7 2015, 13:51:49) 
[GCC 5.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import scrapy
>>> scrapy.__version__
u'1.0.3'
>>> html_body = '''
... <html>
...     <head>
...         <base href="http://b.com/">
...     </head>
...     <body>
...         <form action="test_form">
...         </form>
...     </body>
... </html>
... '''
>>> response = scrapy.http.TextResponse(url='http://a.com/', body=html_body)
>>> request = scrapy.http.FormRequest.from_response(response)
>>> request.url
'http://a.com/test_form'
```
## Expected Result

`request.url` shall be `'http://b.com/test_form'`
## Suggested Fix

The issue can be fixed by fixing a few lines in `scrapy/http/request/form.py`


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `scrapy/http/request/form.py`
Content:
```
1 """
2 This module implements the FormRequest class which is a more convenient class
3 (than Request) to generate Requests based on form data.
4 
5 See documentation in docs/topics/request-response.rst
6 """
7 
8 from six.moves.urllib.parse import urljoin, urlencode
9 import lxml.html
10 from parsel.selector import create_root_node
11 import six
12 from scrapy.http.request import Request
13 from scrapy.utils.python import to_bytes, is_listlike
14 
15 
16 class FormRequest(Request):
17 
18     def __init__(self, *args, **kwargs):
19         formdata = kwargs.pop('formdata', None)
20         if formdata and kwargs.get('method') is None:
21             kwargs['method'] = 'POST'
22 
23         super(FormRequest, self).__init__(*args, **kwargs)
24 
25         if formdata:
26             items = formdata.items() if isinstance(formdata, dict) else formdata
27             querystr = _urlencode(items, self.encoding)
28             if self.method == 'POST':
29                 self.headers.setdefault(b'Content-Type', b'application/x-www-form-urlencoded')
30                 self._set_body(querystr)
31             else:
32                 self._set_url(self.url + ('&' if '?' in self.url else '?') + querystr)
33 
34     @classmethod
35     def from_response(cls, response, formname=None, formid=None, formnumber=0, formdata=None,
36                       clickdata=None, dont_click=False, formxpath=None, **kwargs):
37         kwargs.setdefault('encoding', response.encoding)
38         form = _get_form(response, formname, formid, formnumber, formxpath)
39         formdata = _get_inputs(form, formdata, dont_click, clickdata, response)
40         url = _get_form_url(form, kwargs.pop('url', None))
41         method = kwargs.pop('method', form.method)
42         return cls(url=url, method=method, formdata=formdata, **kwargs)
43 
44 
45 def _get_form_url(form, url):
46     if url is None:
47         return form.action or form.base_url
48     return urljoin(form.base_url, url)
49 
50 
51 def _urlencode(seq, enc):
52     values = [(to_bytes(k, enc), to_bytes(v, enc))
53               for k, vs in seq
54               for v in (vs if is_listlike(vs) else [vs])]
55     return urlencode(values, doseq=1)
56 
57 
58 def _get_form(response, formname, formid, formnumber, formxpath):
59     """Find the form element """
60     text = response.body_as_unicode()
61     root = create_root_node(text, lxml.html.HTMLParser, base_url=response.url)
62     forms = root.xpath('//form')
63     if not forms:
64         raise ValueError("No <form> element found in %s" % response)
65 
66     if formname is not None:
67         f = root.xpath('//form[@name="%s"]' % formname)
68         if f:
69             return f[0]
70 
71     if formid is not None:
72         f = root.xpath('//form[@id="%s"]' % formid)
73         if f:
74             return f[0]
75             
76     # Get form element from xpath, if not found, go up
77     if formxpath is not None:
78         nodes = root.xpath(formxpath)
79         if nodes:
80             el = nodes[0]
81             while True:
82                 if el.tag == 'form':
83                     return el
84                 el = el.getparent()
85                 if el is None:
86                     break
87         raise ValueError('No <form> element found with %s' % formxpath)
88 
89     # If we get here, it means that either formname was None
90     # or invalid
91     if formnumber is not None:
92         try:
93             form = forms[formnumber]
94         except IndexError:
95             raise IndexError("Form number %d not found in %s" %
96                              (formnumber, response))
97         else:
98             return form
99 
100 
101 def _get_inputs(form, formdata, dont_click, clickdata, response):
102     try:
103         formdata = dict(formdata or ())
104     except (ValueError, TypeError):
105         raise ValueError('formdata should be a dict or iterable of tuples')
106 
107     inputs = form.xpath('descendant::textarea'
108                         '|descendant::select'
109                         '|descendant::input[@type!="submit" and @type!="image" and @type!="reset"'
110                         'and ((@type!="checkbox" and @type!="radio") or @checked)]')
111     values = [(k, u'' if v is None else v)
112               for k, v in (_value(e) for e in inputs)
113               if k and k not in formdata]
114 
115     if not dont_click:
116         clickable = _get_clickable(clickdata, form)
117         if clickable and clickable[0] not in formdata and not clickable[0] is None:
118             values.append(clickable)
119 
120     values.extend(formdata.items())
121     return values
122 
123 
124 def _value(ele):
125     n = ele.name
126     v = ele.value
127     if ele.tag == 'select':
128         return _select_value(ele, n, v)
129     return n, v
130 
131 
132 def _select_value(ele, n, v):
133     multiple = ele.multiple
134     if v is None and not multiple:
135         # Match browser behaviour on simple select tag without options selected
136         # And for select tags wihout options
137         o = ele.value_options
138         return (n, o[0]) if o else (None, None)
139     elif v is not None and multiple:
140         # This is a workround to bug in lxml fixed 2.3.1
141         # fix https://github.com/lxml/lxml/commit/57f49eed82068a20da3db8f1b18ae00c1bab8b12#L1L1139
142         selected_options = ele.xpath('.//option[@selected]')
143         v = [(o.get('value') or o.text or u'').strip() for o in selected_options]
144     return n, v
145 
146 
147 def _get_clickable(clickdata, form):
148     """
149     Returns the clickable element specified in clickdata,
150     if the latter is given. If not, it returns the first
151     clickable element found
152     """
153     clickables = [el for el in form.xpath('descendant::input[@type="submit"]'
154                                           '|descendant::button[@type="submit"]'
155                                           '|descendant::button[not(@type)]')]
156     if not clickables:
157         return
158 
159     # If we don't have clickdata, we just use the first clickable element
160     if clickdata is None:
161         el = clickables[0]
162         return (el.get('name'), el.get('value') or '')
163 
164     # If clickdata is given, we compare it to the clickable elements to find a
165     # match. We first look to see if the number is specified in clickdata,
166     # because that uniquely identifies the element
167     nr = clickdata.get('nr', None)
168     if nr is not None:
169         try:
170             el = list(form.inputs)[nr]
171         except IndexError:
172             pass
173         else:
174             return (el.get('name'), el.get('value') or '')
175 
176     # We didn't find it, so now we build an XPath expression out of the other
177     # arguments, because they can be used as such
178     xpath = u'.//*' + \
179             u''.join(u'[@%s="%s"]' % c for c in six.iteritems(clickdata))
180     el = form.xpath(xpath)
181     if len(el) == 1:
182         return (el[0].get('name'), el[0].get('value') or '')
183     elif len(el) > 1:
184         raise ValueError("Multiple elements found (%r) matching the criteria "
185                          "in clickdata: %r" % (el, clickdata))
186     else:
187         raise ValueError('No clickable element matching clickdata: %r' % (clickdata,))
188
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/scrapy/http/request/form.py b/scrapy/http/request/form.py
--- a/scrapy/http/request/form.py
+++ b/scrapy/http/request/form.py
@@ -11,6 +11,7 @@
 import six
 from scrapy.http.request import Request
 from scrapy.utils.python import to_bytes, is_listlike
+from scrapy.utils.response import get_base_url
 
 
 class FormRequest(Request):
@@ -44,7 +45,7 @@
 
 def _get_form_url(form, url):
     if url is None:
-        return form.action or form.base_url
+        return urljoin(form.base_url, form.action)
     return urljoin(form.base_url, url)
 
 
@@ -58,7 +59,7 @@
 def _get_form(response, formname, formid, formnumber, formxpath):
     """Find the form element """
     text = response.body_as_unicode()
-    root = create_root_node(text, lxml.html.HTMLParser, base_url=response.url)
+    root = create_root_node(text, lxml.html.HTMLParser, base_url=get_base_url(response))
     forms = root.xpath('//form')
     if not forms:
         raise ValueError("No <form> element found in %s" % response)

{"golden_diff": "diff --git a/scrapy/http/request/form.py b/scrapy/http/request/form.py\n--- a/scrapy/http/request/form.py\n+++ b/scrapy/http/request/form.py\n@@ -11,6 +11,7 @@\n import six\n from scrapy.http.request import Request\n from scrapy.utils.python import to_bytes, is_listlike\n+from scrapy.utils.response import get_base_url\n \n \n class FormRequest(Request):\n@@ -44,7 +45,7 @@\n \n def _get_form_url(form, url):\n     if url is None:\n-        return form.action or form.base_url\n+        return urljoin(form.base_url, form.action)\n     return urljoin(form.base_url, url)\n \n \n@@ -58,7 +59,7 @@\n def _get_form(response, formname, formid, formnumber, formxpath):\n     \"\"\"Find the form element \"\"\"\n     text = response.body_as_unicode()\n-    root = create_root_node(text, lxml.html.HTMLParser, base_url=response.url)\n+    root = create_root_node(text, lxml.html.HTMLParser, base_url=get_base_url(response))\n     forms = root.xpath('//form')\n     if not forms:\n         raise ValueError(\"No <form> element found in %s\" % response)\n", "issue": "[Bug] Incorrectly picked URL in `scrapy.http.FormRequest.from_response` when there is a `<base>` tag\n## Issue Description\n\nIncorrectly picked URL in `scrapy.http.FormRequest.from_response` when there is a `<base>` tag.\n## How to Reproduce the Issue & Version Used\n\n```\n[pengyu@GLaDOS tmp]$ python2\nPython 2.7.10 (default, Sep  7 2015, 13:51:49) \n[GCC 5.2.0] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import scrapy\n>>> scrapy.__version__\nu'1.0.3'\n>>> html_body = '''\n... <html>\n...     <head>\n...         <base href=\"http://b.com/\">\n...     </head>\n...     <body>\n...         <form action=\"test_form\">\n...         </form>\n...     </body>\n... </html>\n... '''\n>>> response = scrapy.http.TextResponse(url='http://a.com/', body=html_body)\n>>> request = scrapy.http.FormRequest.from_response(response)\n>>> request.url\n'http://a.com/test_form'\n```\n## Expected Result\n\n`request.url` shall be `'http://b.com/test_form'`\n## Suggested Fix\n\nThe issue can be fixed by fixing a few lines in `scrapy/http/request/form.py`\n\n", "before_files": [{"content": "\"\"\"\nThis module implements the FormRequest class which is a more convenient class\n(than Request) to generate Requests based on form data.\n\nSee documentation in docs/topics/request-response.rst\n\"\"\"\n\nfrom six.moves.urllib.parse import urljoin, urlencode\nimport lxml.html\nfrom parsel.selector import create_root_node\nimport six\nfrom scrapy.http.request import Request\nfrom scrapy.utils.python import to_bytes, is_listlike\n\n\nclass FormRequest(Request):\n\n    def __init__(self, *args, **kwargs):\n        formdata = kwargs.pop('formdata', None)\n        if formdata and kwargs.get('method') is None:\n            kwargs['method'] = 'POST'\n\n        super(FormRequest, self).__init__(*args, **kwargs)\n\n        if formdata:\n            items = formdata.items() if isinstance(formdata, dict) else formdata\n            querystr = _urlencode(items, self.encoding)\n            if self.method == 'POST':\n                self.headers.setdefault(b'Content-Type', b'application/x-www-form-urlencoded')\n                self._set_body(querystr)\n            else:\n                self._set_url(self.url + ('&' if '?' in self.url else '?') + querystr)\n\n    @classmethod\n    def from_response(cls, response, formname=None, formid=None, formnumber=0, formdata=None,\n                      clickdata=None, dont_click=False, formxpath=None, **kwargs):\n        kwargs.setdefault('encoding', response.encoding)\n        form = _get_form(response, formname, formid, formnumber, formxpath)\n        formdata = _get_inputs(form, formdata, dont_click, clickdata, response)\n        url = _get_form_url(form, kwargs.pop('url', None))\n        method = kwargs.pop('method', form.method)\n        return cls(url=url, method=method, formdata=formdata, **kwargs)\n\n\ndef _get_form_url(form, url):\n    if url is None:\n        return form.action or form.base_url\n    return urljoin(form.base_url, url)\n\n\ndef _urlencode(seq, enc):\n    values = [(to_bytes(k, enc), to_bytes(v, enc))\n              for k, vs in seq\n              for v in (vs if is_listlike(vs) else [vs])]\n    return urlencode(values, doseq=1)\n\n\ndef _get_form(response, formname, formid, formnumber, formxpath):\n    \"\"\"Find the form element \"\"\"\n    text = response.body_as_unicode()\n    root = create_root_node(text, lxml.html.HTMLParser, base_url=response.url)\n    forms = root.xpath('//form')\n    if not forms:\n        raise ValueError(\"No <form> element found in %s\" % response)\n\n    if formname is not None:\n        f = root.xpath('//form[@name=\"%s\"]' % formname)\n        if f:\n            return f[0]\n\n    if formid is not None:\n        f = root.xpath('//form[@id=\"%s\"]' % formid)\n        if f:\n            return f[0]\n            \n    # Get form element from xpath, if not found, go up\n    if formxpath is not None:\n        nodes = root.xpath(formxpath)\n        if nodes:\n            el = nodes[0]\n            while True:\n                if el.tag == 'form':\n                    return el\n                el = el.getparent()\n                if el is None:\n                    break\n        raise ValueError('No <form> element found with %s' % formxpath)\n\n    # If we get here, it means that either formname was None\n    # or invalid\n    if formnumber is not None:\n        try:\n            form = forms[formnumber]\n        except IndexError:\n            raise IndexError(\"Form number %d not found in %s\" %\n                             (formnumber, response))\n        else:\n            return form\n\n\ndef _get_inputs(form, formdata, dont_click, clickdata, response):\n    try:\n        formdata = dict(formdata or ())\n    except (ValueError, TypeError):\n        raise ValueError('formdata should be a dict or iterable of tuples')\n\n    inputs = form.xpath('descendant::textarea'\n                        '|descendant::select'\n                        '|descendant::input[@type!=\"submit\" and @type!=\"image\" and @type!=\"reset\"'\n                        'and ((@type!=\"checkbox\" and @type!=\"radio\") or @checked)]')\n    values = [(k, u'' if v is None else v)\n              for k, v in (_value(e) for e in inputs)\n              if k and k not in formdata]\n\n    if not dont_click:\n        clickable = _get_clickable(clickdata, form)\n        if clickable and clickable[0] not in formdata and not clickable[0] is None:\n            values.append(clickable)\n\n    values.extend(formdata.items())\n    return values\n\n\ndef _value(ele):\n    n = ele.name\n    v = ele.value\n    if ele.tag == 'select':\n        return _select_value(ele, n, v)\n    return n, v\n\n\ndef _select_value(ele, n, v):\n    multiple = ele.multiple\n    if v is None and not multiple:\n        # Match browser behaviour on simple select tag without options selected\n        # And for select tags wihout options\n        o = ele.value_options\n        return (n, o[0]) if o else (None, None)\n    elif v is not None and multiple:\n        # This is a workround to bug in lxml fixed 2.3.1\n        # fix https://github.com/lxml/lxml/commit/57f49eed82068a20da3db8f1b18ae00c1bab8b12#L1L1139\n        selected_options = ele.xpath('.//option[@selected]')\n        v = [(o.get('value') or o.text or u'').strip() for o in selected_options]\n    return n, v\n\n\ndef _get_clickable(clickdata, form):\n    \"\"\"\n    Returns the clickable element specified in clickdata,\n    if the latter is given. If not, it returns the first\n    clickable element found\n    \"\"\"\n    clickables = [el for el in form.xpath('descendant::input[@type=\"submit\"]'\n                                          '|descendant::button[@type=\"submit\"]'\n                                          '|descendant::button[not(@type)]')]\n    if not clickables:\n        return\n\n    # If we don't have clickdata, we just use the first clickable element\n    if clickdata is None:\n        el = clickables[0]\n        return (el.get('name'), el.get('value') or '')\n\n    # If clickdata is given, we compare it to the clickable elements to find a\n    # match. We first look to see if the number is specified in clickdata,\n    # because that uniquely identifies the element\n    nr = clickdata.get('nr', None)\n    if nr is not None:\n        try:\n            el = list(form.inputs)[nr]\n        except IndexError:\n            pass\n        else:\n            return (el.get('name'), el.get('value') or '')\n\n    # We didn't find it, so now we build an XPath expression out of the other\n    # arguments, because they can be used as such\n    xpath = u'.//*' + \\\n            u''.join(u'[@%s=\"%s\"]' % c for c in six.iteritems(clickdata))\n    el = form.xpath(xpath)\n    if len(el) == 1:\n        return (el[0].get('name'), el[0].get('value') or '')\n    elif len(el) > 1:\n        raise ValueError(\"Multiple elements found (%r) matching the criteria \"\n                         \"in clickdata: %r\" % (el, clickdata))\n    else:\n        raise ValueError('No clickable element matching clickdata: %r' % (clickdata,))\n", "path": "scrapy/http/request/form.py"}], "after_files": [{"content": "\"\"\"\nThis module implements the FormRequest class which is a more convenient class\n(than Request) to generate Requests based on form data.\n\nSee documentation in docs/topics/request-response.rst\n\"\"\"\n\nfrom six.moves.urllib.parse import urljoin, urlencode\nimport lxml.html\nfrom parsel.selector import create_root_node\nimport six\nfrom scrapy.http.request import Request\nfrom scrapy.utils.python import to_bytes, is_listlike\nfrom scrapy.utils.response import get_base_url\n\n\nclass FormRequest(Request):\n\n    def __init__(self, *args, **kwargs):\n        formdata = kwargs.pop('formdata', None)\n        if formdata and kwargs.get('method') is None:\n            kwargs['method'] = 'POST'\n\n        super(FormRequest, self).__init__(*args, **kwargs)\n\n        if formdata:\n            items = formdata.items() if isinstance(formdata, dict) else formdata\n            querystr = _urlencode(items, self.encoding)\n            if self.method == 'POST':\n                self.headers.setdefault(b'Content-Type', b'application/x-www-form-urlencoded')\n                self._set_body(querystr)\n            else:\n                self._set_url(self.url + ('&' if '?' in self.url else '?') + querystr)\n\n    @classmethod\n    def from_response(cls, response, formname=None, formid=None, formnumber=0, formdata=None,\n                      clickdata=None, dont_click=False, formxpath=None, **kwargs):\n        kwargs.setdefault('encoding', response.encoding)\n        form = _get_form(response, formname, formid, formnumber, formxpath)\n        formdata = _get_inputs(form, formdata, dont_click, clickdata, response)\n        url = _get_form_url(form, kwargs.pop('url', None))\n        method = kwargs.pop('method', form.method)\n        return cls(url=url, method=method, formdata=formdata, **kwargs)\n\n\ndef _get_form_url(form, url):\n    if url is None:\n        return urljoin(form.base_url, form.action)\n    return urljoin(form.base_url, url)\n\n\ndef _urlencode(seq, enc):\n    values = [(to_bytes(k, enc), to_bytes(v, enc))\n              for k, vs in seq\n              for v in (vs if is_listlike(vs) else [vs])]\n    return urlencode(values, doseq=1)\n\n\ndef _get_form(response, formname, formid, formnumber, formxpath):\n    \"\"\"Find the form element \"\"\"\n    text = response.body_as_unicode()\n    root = create_root_node(text, lxml.html.HTMLParser, base_url=get_base_url(response))\n    forms = root.xpath('//form')\n    if not forms:\n        raise ValueError(\"No <form> element found in %s\" % response)\n\n    if formname is not None:\n        f = root.xpath('//form[@name=\"%s\"]' % formname)\n        if f:\n            return f[0]\n\n    if formid is not None:\n        f = root.xpath('//form[@id=\"%s\"]' % formid)\n        if f:\n            return f[0]\n            \n    # Get form element from xpath, if not found, go up\n    if formxpath is not None:\n        nodes = root.xpath(formxpath)\n        if nodes:\n            el = nodes[0]\n            while True:\n                if el.tag == 'form':\n                    return el\n                el = el.getparent()\n                if el is None:\n                    break\n        raise ValueError('No <form> element found with %s' % formxpath)\n\n    # If we get here, it means that either formname was None\n    # or invalid\n    if formnumber is not None:\n        try:\n            form = forms[formnumber]\n        except IndexError:\n            raise IndexError(\"Form number %d not found in %s\" %\n                             (formnumber, response))\n        else:\n            return form\n\n\ndef _get_inputs(form, formdata, dont_click, clickdata, response):\n    try:\n        formdata = dict(formdata or ())\n    except (ValueError, TypeError):\n        raise ValueError('formdata should be a dict or iterable of tuples')\n\n    inputs = form.xpath('descendant::textarea'\n                        '|descendant::select'\n                        '|descendant::input[@type!=\"submit\" and @type!=\"image\" and @type!=\"reset\"'\n                        'and ((@type!=\"checkbox\" and @type!=\"radio\") or @checked)]')\n    values = [(k, u'' if v is None else v)\n              for k, v in (_value(e) for e in inputs)\n              if k and k not in formdata]\n\n    if not dont_click:\n        clickable = _get_clickable(clickdata, form)\n        if clickable and clickable[0] not in formdata and not clickable[0] is None:\n            values.append(clickable)\n\n    values.extend(formdata.items())\n    return values\n\n\ndef _value(ele):\n    n = ele.name\n    v = ele.value\n    if ele.tag == 'select':\n        return _select_value(ele, n, v)\n    return n, v\n\n\ndef _select_value(ele, n, v):\n    multiple = ele.multiple\n    if v is None and not multiple:\n        # Match browser behaviour on simple select tag without options selected\n        # And for select tags wihout options\n        o = ele.value_options\n        return (n, o[0]) if o else (None, None)\n    elif v is not None and multiple:\n        # This is a workround to bug in lxml fixed 2.3.1\n        # fix https://github.com/lxml/lxml/commit/57f49eed82068a20da3db8f1b18ae00c1bab8b12#L1L1139\n        selected_options = ele.xpath('.//option[@selected]')\n        v = [(o.get('value') or o.text or u'').strip() for o in selected_options]\n    return n, v\n\n\ndef _get_clickable(clickdata, form):\n    \"\"\"\n    Returns the clickable element specified in clickdata,\n    if the latter is given. If not, it returns the first\n    clickable element found\n    \"\"\"\n    clickables = [el for el in form.xpath('descendant::input[@type=\"submit\"]'\n                                          '|descendant::button[@type=\"submit\"]'\n                                          '|descendant::button[not(@type)]')]\n    if not clickables:\n        return\n\n    # If we don't have clickdata, we just use the first clickable element\n    if clickdata is None:\n        el = clickables[0]\n        return (el.get('name'), el.get('value') or '')\n\n    # If clickdata is given, we compare it to the clickable elements to find a\n    # match. We first look to see if the number is specified in clickdata,\n    # because that uniquely identifies the element\n    nr = clickdata.get('nr', None)\n    if nr is not None:\n        try:\n            el = list(form.inputs)[nr]\n        except IndexError:\n            pass\n        else:\n            return (el.get('name'), el.get('value') or '')\n\n    # We didn't find it, so now we build an XPath expression out of the other\n    # arguments, because they can be used as such\n    xpath = u'.//*' + \\\n            u''.join(u'[@%s=\"%s\"]' % c for c in six.iteritems(clickdata))\n    el = form.xpath(xpath)\n    if len(el) == 1:\n        return (el[0].get('name'), el[0].get('value') or '')\n    elif len(el) > 1:\n        raise ValueError(\"Multiple elements found (%r) matching the criteria \"\n                         \"in clickdata: %r\" % (el, clickdata))\n    else:\n        raise ValueError('No clickable element matching clickdata: %r' % (clickdata,))\n", "path": "scrapy/http/request/form.py"}]}