Skip to content

Instantly share code, notes, and snippets.

@softplus
Last active May 5, 2023 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save softplus/164cffc6af8cdbee1f38bbe9e0ee4d79 to your computer and use it in GitHub Desktop.
Save softplus/164cffc6af8cdbee1f38bbe9e0ee4d79 to your computer and use it in GitHub Desktop.
Submit new values to a Google Form for a Google Sheet using Python, without the Google APIs
#!/usr/bin/python
"""Posts to a Google Sheet using a Form"""
import re
import sys
import urllib
import urllib2
def get_field_ids(form_url):
"""Returns list of field IDs on the form."""
response = urllib2.urlopen(form_url)
html = response.read()
form_field_info = re.findall('(<input|<textarea)[^>]*id="([^"]*)"', html)
if form_field_info: # depends on UI version
fields = [x[1] for x in form_field_info if x[1].startswith("entry")]
else:
form_field_info = re.findall('\[\[([0-9]{3,30}),null,0\]\]', html)
fields = ["entry."+x for x in form_field_info]
return fields
def post_form_values(form_url, submit_values):
"""Posts list of values to the form."""
fields = get_field_ids(form_url) # these could be cached too.
submit_url = form_url.replace("/viewform", "/formResponse")
values = {}
for counter in range(0, min(len(submit_values), len(fields))):
values[fields[counter]] = submit_values[counter]
data = urllib.urlencode(values)
req = urllib2.Request(submit_url, data)
response = urllib2.urlopen(req)
the_page = response.read()
# ignore response
def main():
"""Command-line usage possible too!"""
if len(sys.argv)<3:
print "Expected: form_url value1 [value2 ...]"
return
form_url = sys.argv[1]
values = sys.argv[2:]
post_form_values(form_url, values)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment