MCPcopy Create free account
hub / github.com/gawel/pyquery / fromstring

Function fromstring

pyquery/pyquery.py:67–109  ·  view source on GitHub ↗

use html parser if we don't have clean xml

(context, parser=None, custom_parser=None)

Source from the content-addressed store, hash-verified

65
66
67def 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
112def callback(func, *args):

Callers 5

__init__Method · 0.85
htmlMethod · 0.85
_get_rootMethod · 0.85
wrapMethod · 0.85
wrap_allMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…