I wanted a way to open up pages in my web browser with Python, but perform a POST request, sending data along with it. This functionality is not supported by the webbrowser module, nor do I see how it could. So, I came up with solution that meets my needs. It involves jQuery and creating then deleting a temporary file.
For those of you who do not know, jQuery is a JavaScript library that makes programming in JavaScript downright enjoyable, and provides easy solutions to common problems. Google has a Javascript API that lets you easily download stable versions of many different JavaScript libraries, including jQuery. You can do this wherever you would like, and makes it so you don't have to keep the source local (there are many benefits to this approach).
So, these are the steps we take to open a page with Python, and post our predefined (hard-coded or dynamic) form data to a page our our liking:
- Dynamically create a complete HTML file.
- Include jQuery on the page (this makes it much easier to know when the form is ready for submission).
- Create a form on the page with the appropriate action and method.
- Insert hidden form elements with their corresponding names and values.
- Submit the form when the DOM is finished (jQuery helps with that).
- Delete the file when we are done.
import os
import webbrowser
# Set up form elements - these will become the input elements in the form
input_value = {
'Passwd' : 'YOUR PASSWORD HERE',
'Email' : 'YOUR USER NAME',
'continue': 'https://mail.google.com'
}
action='https://www.google.com/accounts/ServiceLoginAuth?service=mail'
method='post'
#Set up javascript form submition function.
# I am using the 'format' function on a string, and it doesn't like the { and } of the js function
# so I brought it out to be inserted later
js_submit = '$(document).ready(function() {$("#form").submit(); });'
# Set up file content elements
input_field = '<input type="hidden" name="{0}" value="{1}" />'
base_file_contents = """
<script src='http://www.google.com/jsapi'></script>
<script>
google.load('jquery', '1.3.2');
</script>
<script>
{0}
</script>
<form id='form' action='{1}' method='{2}' />
{3}
</form>
"""
# Build input fields
input_fields = ""
for key, value in input_value.items():
input_fields += input_field.format(key, value)
# Open web page
with open('temp_file.html', "w") as file:
file.write(base_file_contents.format(js_submit,action, method, input_fields))
file.close()
webbrowser.open(os.path.abspath(file.name))
os.remove(os.path.abspath(file.name))
Let me know if you find this useful!
Great work.
ReplyDeleteSee also the project at http://www.contactexter.com/
Great, thanks a lot, it's what I was looking for. It's 2017 and it works :) I had to put a sleep before deleting the file otherwise in the browser appear the message that the file doesn't exists.
ReplyDeleteMike