util.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import time
  2. import random
  3. def type(e, text, delay=0.1):
  4. for c in text:
  5. e.type(c)
  6. sleep(0, delay)
  7. def filter_by_value(elements, values):
  8. if not isinstance(values, list):
  9. values = [values]
  10. return [e for e in elements if e.value.strip() in values]
  11. def sleep(min_delay, random_delay):
  12. time.sleep(min_delay + random_delay * random.random())
  13. def _get_tag_ids_single(html, tag):
  14. start_idx = 0
  15. res = []
  16. while html.find(tag, start_idx) >= 0:
  17. idx = html.find(tag, start_idx)
  18. s = idx
  19. while html[s] != '<':
  20. s -= 1
  21. e = idx
  22. while html[e] != '>':
  23. e += 1
  24. id_start_idx = html.find('id="', s) + 4
  25. id_end_idx = html.find('"', id_start_idx)
  26. if id_start_idx < s or id_start_idx > e or id_end_idx < s or id_end_idx > e:
  27. print 'could not find id in %s' % html[s:e]
  28. start_idx = idx + 1
  29. continue
  30. res.append(html[id_start_idx:id_end_idx])
  31. start_idx = idx + 1
  32. return res
  33. def get_tag_ids(html, tags):
  34. if isinstance(tags, list):
  35. for tag in tags:
  36. res = _get_tag_ids_single(html, tag)
  37. if res:
  38. return res
  39. return []
  40. else:
  41. return _get_tag_ids_single(html, tag)