/staticmobilewebsites/py/markup_ex12b.py

http://mwta.googlecode.com/ · Python · 64 lines · 24 code · 6 blank · 34 comment · 3 complexity · c2b359eb7b96e58871510517bb870c54 MD5 · raw file

  1. # Copyright 2009 mwta committers
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License
  14. """ Markup Example 12
  15. Adding a user-agent string to emulate a Nokia 6230
  16. """
  17. import urllib
  18. import re
  19. import amara
  20. def getHrefFromXML(doc, search_regex):
  21. """Returns the href link if the in search_regex is
  22. found in any <div> tags.
  23. Assumes the links are in the html body's div tags.
  24. Args:
  25. doc: an amara xml object
  26. search_regex: the regular expression to match in
  27. the href text
  28. Returns:
  29. the href as a string if the pattern is found, else None.
  30. """
  31. ru1 = re.compile(search_regex)
  32. for item in doc.html.body.div:
  33. try:
  34. # print str(item.a.xml_children[0])
  35. # print type(item.a.xml_children[0])
  36. p = ru1.search(item.a.xml_children[0])
  37. if p:
  38. return item.a.href
  39. except:
  40. pass
  41. return None
  42. if __name__ == "__main__":
  43. request = urllib.FancyURLopener()
  44. request.addheader('Accept', 'application/xhtml+xml')
  45. request.addheader('User-Agent', 'Nokia6230/2.0+(04.43)'
  46. '+Profile/MIDP-2.0+Configuration'
  47. '/CLDC-1.1+UP.Link/6.3.0.0.0')
  48. response = request.open("http://www.google.co.uk/m")
  49. content = response.read()
  50. # Use the live content
  51. doc = amara.parse(content)
  52. print "should return: '/gmm?source=m&dc=mobile-promotion'"
  53. print getHrefFromXML(doc, "Maps")