Skip to content

Instantly share code, notes, and snippets.

@sarim
Created September 7, 2015 11:39
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 sarim/578a678450712f0ce0c5 to your computer and use it in GitHub Desktop.
Save sarim/578a678450712f0ce0c5 to your computer and use it in GitHub Desktop.
from lxml.html import fromstring, tostring
from pprint import pprint
from inspect import getmembers
from more_itertools import unique_everseen
form_page = fromstring(open('postProduct.html').read())
form = form_page.forms[0]
def printlabel(v):
l = v.getparent().find('label')
if l is not None:
t = '<label class="item item-input">\n <span class="input-label">%s</span>\n <input type="%s" name="%s" value="%s">\n</label>'
t2 = '<label class="item item-input">\n <span class="input-label">%s</span>\n <input type="%s" name="%s">\n</label>'
try:
if 'value' in v.attrib:
print t % (l.text_content(), v.attrib['type'], v.attrib['name'], v.attrib['value'])
else:
print t2 % (l.text_content(), v.attrib['type'], v.attrib['name'])
except Exception as e:
print "Error", v
def printcheckbox(v):
l = v.getparent().find('label')
if l is not None:
t = '<div class="item item-checkbox">\n <label class="checkbox">\n <input type="%s" name="%s" value="%s">\n </label>\n %s\n</div>'
print t % (v.attrib['type'], v.attrib['name'], v.attrib['value'], v.attrib['value'])
def printoption(v):
return tostring(v).strip()
def printselect(v):
l = v.getparent().find('label')
if l is not None:
t = '<label class="item item-input item-select">\n <div class="input-label">%s</div>\n <select name="%s">\n %s\n </select>\n</label>'
options = map(printoption, v.findall('option'));
print t % (l.text_content(), v.attrib['name'], "\n ".join(options))
def printtextarea(v):
l = v.getparent().find('label')
if l is not None:
t = '<label class="item item-input">\n <span class="input-label">%s</span>\n <textarea name="%s"></textarea>\n</label>'
print t % (l.text_content(), v.attrib['name'])
orderedKeyNames = unique_everseen( map(lambda e: e.attrib['name'], form.inputs))
for k in orderedKeyNames:
v = form.inputs[k]
if isinstance(v, (list, tuple)):
if v.__class__.__name__ == "CheckboxGroup":
map(printcheckbox, v)
elif v.__class__.__name__ == "SelectElement":
printselect(v)
elif v.__class__.__name__ == "TextareaElement":
printtextarea(v)
else:
printlabel(v)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment