5

I have a button on a page that needs to be clicked for me to move on to the next page in a sequence, and I was wondering how this is possible with Python. The button seems to be the mix of an HTTP POST request and Javascript, here is the code for the button:

<FORM name="ff" action="nq2.phtml" method="post">
  <INPUT type="hidden" name="target" value="-1">
  <INPUT type="hidden" name="fact" value="">
  <INPUT type="hidden" name="parm" value="">
  <INPUT type="hidden" name="use_id" value="-1">
  <INPUT type="hidden" name="nxactor" value="1">
  <TD align="center" valign="top">
  <DIV class="pr">
  <A href="javascript:;" onClick="settarget(5); setch(ch5); return false;">

I honestly have no idea how to approach something like this and was wondering if anyone had some insight about how I would go about doing it.

jcollado
  • 39,419
  • 8
  • 102
  • 133
Dan Doe
  • 1,146
  • 3
  • 14
  • 25

1 Answers1

6

To simulate the submission of a form, you can send the same POST request that your browser will send to the site once the submit button is clicked. One way to do this is use urllib.urlencode to encode the form data from a dictionary and urllib2.urlopen to send the request:

import urllib, urllib2
form_data = urllib.urlencode({'target': <value>, 'fact': <value>, ...})
urllib2.urlopen("np2.phtml", form_data)
TerryA
  • 58,805
  • 11
  • 114
  • 143
jcollado
  • 39,419
  • 8
  • 102
  • 133
  • Hey, I'm dealing with a similar problem. The issue is that when I click the button it generates a hash which is sent to the website (so there is no way to know the POST request beforehand). what should one do in such a situation? – Nazim Kerimbekov Feb 23 '19 at 18:49
  • @Fozoro You might be dealing with a single page application. In that case, I'd try to reproduce the scenario you're interested in with something like [selenium](https://www.seleniumhq.org/) or [cypress](https://www.cypress.io/). – jcollado Feb 24 '19 at 13:02
  • Great, thank you very much for your reply, I never heard of cypress before (will take a look into it). Nonetheless are you aware if this is even possible using the requests module (without selenium). Many thanks for your answer in advance. – Nazim Kerimbekov Feb 24 '19 at 13:24
  • @Fozoro I'm afraid that sometimes you need to execute javascript code to get what you need and it looks like you're in that case. – jcollado Feb 26 '19 at 18:18