use html parser if we don't have clean xml
(context, parser=None, custom_parser=None)
| 65 | |
| 66 | |
| 67 | def fromstring(context, parser=None, custom_parser=None): |
| 68 | """use html parser if we don't have clean xml |
| 69 | """ |
| 70 | if hasattr(context, 'read') and hasattr(context.read, '__call__'): |
| 71 | meth = 'parse' |
| 72 | else: |
| 73 | meth = 'fromstring' |
| 74 | if custom_parser is None: |
| 75 | if parser is None: |
| 76 | try: |
| 77 | result = getattr(etree, meth)(context) |
| 78 | except etree.XMLSyntaxError: |
| 79 | if hasattr(context, 'seek'): |
| 80 | context.seek(0) |
| 81 | result = getattr(lxml.html, meth)(context) |
| 82 | if isinstance(result, etree._ElementTree): |
| 83 | return [result.getroot()] |
| 84 | else: |
| 85 | return [result] |
| 86 | elif parser == 'xml': |
| 87 | custom_parser = getattr(etree, meth) |
| 88 | elif parser == 'html': |
| 89 | custom_parser = getattr(lxml.html, meth) |
| 90 | elif parser == 'html5': |
| 91 | from lxml.html import html5parser |
| 92 | custom_parser = getattr(html5parser, meth) |
| 93 | elif parser == 'soup': |
| 94 | from lxml.html import soupparser |
| 95 | custom_parser = getattr(soupparser, meth) |
| 96 | elif parser == 'html_fragments': |
| 97 | custom_parser = lxml.html.fragments_fromstring |
| 98 | else: |
| 99 | raise ValueError('No such parser: "%s"' % parser) |
| 100 | |
| 101 | result = custom_parser(context) |
| 102 | if isinstance(result, list): |
| 103 | return result |
| 104 | elif isinstance(result, etree._ElementTree): |
| 105 | return [result.getroot()] |
| 106 | elif result is not None: |
| 107 | return [result] |
| 108 | else: |
| 109 | return [] |
| 110 | |
| 111 | |
| 112 | def callback(func, *args): |