diff --git a/README.rst b/README.rst index 59aa759..73f9da6 100644 --- a/README.rst +++ b/README.rst @@ -41,6 +41,17 @@ And it is possible to use it as a tool to quickly debug a login form:: - password: secret +You can also provide a selector to the method as an XPath so select a particular form on the page. +This can be useful if you have more than one form present, and the score mechanism selects the incorrect form:: + + >>> from loginform import fill_login_form + >>> import requests + >>> url = "https://twitter.com" + >>> r = requests.get(url) + >>> fill_login_form(url, r.text, "john", "secret", selector='//form[@class="signin"]') + >>> fill_login_form(url, r.text, "john", "secret", selector='//form[@class="signup"]') + + Testing ------- diff --git a/loginform.py b/loginform.py index bb3fa24..b3d46a8 100644 --- a/loginform.py +++ b/loginform.py @@ -39,6 +39,8 @@ def _form_score(form): def _pick_form(forms): """Return the form most likely to be a login form""" + for form in forms: + print(form) return sorted(forms, key=_form_score, reverse=True)[0] @@ -72,9 +74,12 @@ def submit_value(form): return [] -def fill_login_form(url, body, username, password): +def fill_login_form(url, body, username, password, *args, **kwargs): + + selector = kwargs.get('selector', '//form') + doc = html.document_fromstring(body, base_url=url) - form = _pick_form(doc.xpath('//form')) + form = _pick_form(doc.xpath(selector)) userfield, passfield = _pick_fields(form) form.fields[userfield] = username form.fields[passfield] = password diff --git a/test_samples.py b/test_samples.py index 72b9b49..b0ae4fe 100644 --- a/test_samples.py +++ b/test_samples.py @@ -48,8 +48,13 @@ def main(): if opts.list: print("\n".join(list_samples())) else: + print(args) url = args[0] - r = requests.get(url) + headers = { + 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)', + } + + r = requests.get(url, headers=headers) values = fill_login_form(url, r.text, "USER", "PASS") values = (url, values) print(json.dumps(values, indent=3))