You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

314 lines
10 KiB

4 years ago
  1. """External interface to the BeautifulSoup HTML parser.
  2. """
  3. __all__ = ["fromstring", "parse", "convert_tree"]
  4. import re
  5. from lxml import etree, html
  6. try:
  7. from bs4 import (
  8. BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString,
  9. Declaration, Doctype)
  10. _DECLARATION_OR_DOCTYPE = (Declaration, Doctype)
  11. except ImportError:
  12. from BeautifulSoup import (
  13. BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString,
  14. Declaration)
  15. _DECLARATION_OR_DOCTYPE = Declaration
  16. def fromstring(data, beautifulsoup=None, makeelement=None, **bsargs):
  17. """Parse a string of HTML data into an Element tree using the
  18. BeautifulSoup parser.
  19. Returns the root ``<html>`` Element of the tree.
  20. You can pass a different BeautifulSoup parser through the
  21. `beautifulsoup` keyword, and a diffent Element factory function
  22. through the `makeelement` keyword. By default, the standard
  23. ``BeautifulSoup`` class and the default factory of `lxml.html` are
  24. used.
  25. """
  26. return _parse(data, beautifulsoup, makeelement, **bsargs)
  27. def parse(file, beautifulsoup=None, makeelement=None, **bsargs):
  28. """Parse a file into an ElemenTree using the BeautifulSoup parser.
  29. You can pass a different BeautifulSoup parser through the
  30. `beautifulsoup` keyword, and a diffent Element factory function
  31. through the `makeelement` keyword. By default, the standard
  32. ``BeautifulSoup`` class and the default factory of `lxml.html` are
  33. used.
  34. """
  35. if not hasattr(file, 'read'):
  36. file = open(file)
  37. root = _parse(file, beautifulsoup, makeelement, **bsargs)
  38. return etree.ElementTree(root)
  39. def convert_tree(beautiful_soup_tree, makeelement=None):
  40. """Convert a BeautifulSoup tree to a list of Element trees.
  41. Returns a list instead of a single root Element to support
  42. HTML-like soup with more than one root element.
  43. You can pass a different Element factory through the `makeelement`
  44. keyword.
  45. """
  46. root = _convert_tree(beautiful_soup_tree, makeelement)
  47. children = root.getchildren()
  48. for child in children:
  49. root.remove(child)
  50. return children
  51. # helpers
  52. def _parse(source, beautifulsoup, makeelement, **bsargs):
  53. if beautifulsoup is None:
  54. beautifulsoup = BeautifulSoup
  55. if hasattr(beautifulsoup, "HTML_ENTITIES"): # bs3
  56. if 'convertEntities' not in bsargs:
  57. bsargs['convertEntities'] = 'html'
  58. if hasattr(beautifulsoup, "DEFAULT_BUILDER_FEATURES"): # bs4
  59. if 'features' not in bsargs:
  60. bsargs['features'] = 'html.parser' # use Python html parser
  61. tree = beautifulsoup(source, **bsargs)
  62. root = _convert_tree(tree, makeelement)
  63. # from ET: wrap the document in a html root element, if necessary
  64. if len(root) == 1 and root[0].tag == "html":
  65. return root[0]
  66. root.tag = "html"
  67. return root
  68. _parse_doctype_declaration = re.compile(
  69. r'(?:\s|[<!])*DOCTYPE\s*HTML'
  70. r'(?:\s+PUBLIC)?(?:\s+(\'[^\']*\'|"[^"]*"))?'
  71. r'(?:\s+(\'[^\']*\'|"[^"]*"))?',
  72. re.IGNORECASE).match
  73. class _PseudoTag:
  74. # Minimal imitation of BeautifulSoup.Tag
  75. def __init__(self, contents):
  76. self.name = 'html'
  77. self.attrs = []
  78. self.contents = contents
  79. def __iter__(self):
  80. return self.contents.__iter__()
  81. def _convert_tree(beautiful_soup_tree, makeelement):
  82. if makeelement is None:
  83. makeelement = html.html_parser.makeelement
  84. # Split the tree into three parts:
  85. # i) everything before the root element: document type
  86. # declaration, comments, processing instructions, whitespace
  87. # ii) the root(s),
  88. # iii) everything after the root: comments, processing
  89. # instructions, whitespace
  90. first_element_idx = last_element_idx = None
  91. html_root = declaration = None
  92. for i, e in enumerate(beautiful_soup_tree):
  93. if isinstance(e, Tag):
  94. if first_element_idx is None:
  95. first_element_idx = i
  96. last_element_idx = i
  97. if html_root is None and e.name and e.name.lower() == 'html':
  98. html_root = e
  99. elif declaration is None and isinstance(e, _DECLARATION_OR_DOCTYPE):
  100. declaration = e
  101. # For a nice, well-formatted document, the variable roots below is
  102. # a list consisting of a single <html> element. However, the document
  103. # may be a soup like '<meta><head><title>Hello</head><body>Hi
  104. # all<\p>'. In this example roots is a list containing meta, head
  105. # and body elements.
  106. if first_element_idx is None:
  107. pre_root = post_root = []
  108. roots = beautiful_soup_tree.contents
  109. else:
  110. pre_root = beautiful_soup_tree.contents[:first_element_idx]
  111. roots = beautiful_soup_tree.contents[first_element_idx:last_element_idx+1]
  112. post_root = beautiful_soup_tree.contents[last_element_idx+1:]
  113. # Reorganize so that there is one <html> root...
  114. if html_root is not None:
  115. # ... use existing one if possible, ...
  116. i = roots.index(html_root)
  117. html_root.contents = roots[:i] + html_root.contents + roots[i+1:]
  118. else:
  119. # ... otherwise create a new one.
  120. html_root = _PseudoTag(roots)
  121. convert_node = _init_node_converters(makeelement)
  122. # Process pre_root
  123. res_root = convert_node(html_root)
  124. prev = res_root
  125. for e in reversed(pre_root):
  126. converted = convert_node(e)
  127. if converted is not None:
  128. prev.addprevious(converted)
  129. prev = converted
  130. # ditto for post_root
  131. prev = res_root
  132. for e in post_root:
  133. converted = convert_node(e)
  134. if converted is not None:
  135. prev.addnext(converted)
  136. prev = converted
  137. if declaration is not None:
  138. try:
  139. # bs4 provides full Doctype string
  140. doctype_string = declaration.output_ready()
  141. except AttributeError:
  142. doctype_string = declaration.string
  143. match = _parse_doctype_declaration(doctype_string)
  144. if not match:
  145. # Something is wrong if we end up in here. Since soupparser should
  146. # tolerate errors, do not raise Exception, just let it pass.
  147. pass
  148. else:
  149. external_id, sys_uri = match.groups()
  150. docinfo = res_root.getroottree().docinfo
  151. # strip quotes and update DOCTYPE values (any of None, '', '...')
  152. docinfo.public_id = external_id and external_id[1:-1]
  153. docinfo.system_url = sys_uri and sys_uri[1:-1]
  154. return res_root
  155. def _init_node_converters(makeelement):
  156. converters = {}
  157. ordered_node_types = []
  158. def converter(*types):
  159. def add(handler):
  160. for t in types:
  161. converters[t] = handler
  162. ordered_node_types.append(t)
  163. return handler
  164. return add
  165. def find_best_converter(node):
  166. for t in ordered_node_types:
  167. if isinstance(node, t):
  168. return converters[t]
  169. return None
  170. def convert_node(bs_node, parent=None):
  171. # duplicated in convert_tag() below
  172. try:
  173. handler = converters[type(bs_node)]
  174. except KeyError:
  175. handler = converters[type(bs_node)] = find_best_converter(bs_node)
  176. if handler is None:
  177. return None
  178. return handler(bs_node, parent)
  179. def map_attrs(bs_attrs):
  180. if isinstance(bs_attrs, dict): # bs4
  181. attribs = {}
  182. for k, v in bs_attrs.items():
  183. if isinstance(v, list):
  184. v = " ".join(v)
  185. attribs[k] = unescape(v)
  186. else:
  187. attribs = dict((k, unescape(v)) for k, v in bs_attrs)
  188. return attribs
  189. def append_text(parent, text):
  190. if len(parent) == 0:
  191. parent.text = (parent.text or '') + text
  192. else:
  193. parent[-1].tail = (parent[-1].tail or '') + text
  194. # converters are tried in order of their definition
  195. @converter(Tag, _PseudoTag)
  196. def convert_tag(bs_node, parent):
  197. attrs = bs_node.attrs
  198. if parent is not None:
  199. attribs = map_attrs(attrs) if attrs else None
  200. res = etree.SubElement(parent, bs_node.name, attrib=attribs)
  201. else:
  202. attribs = map_attrs(attrs) if attrs else {}
  203. res = makeelement(bs_node.name, attrib=attribs)
  204. for child in bs_node:
  205. # avoid double recursion by inlining convert_node(), see above
  206. try:
  207. handler = converters[type(child)]
  208. except KeyError:
  209. pass
  210. else:
  211. if handler is not None:
  212. handler(child, res)
  213. continue
  214. convert_node(child, res)
  215. return res
  216. @converter(Comment)
  217. def convert_comment(bs_node, parent):
  218. res = html.HtmlComment(bs_node)
  219. if parent is not None:
  220. parent.append(res)
  221. return res
  222. @converter(ProcessingInstruction)
  223. def convert_pi(bs_node, parent):
  224. if bs_node.endswith('?'):
  225. # The PI is of XML style (<?as df?>) but BeautifulSoup
  226. # interpreted it as being SGML style (<?as df>). Fix.
  227. bs_node = bs_node[:-1]
  228. res = etree.ProcessingInstruction(*bs_node.split(' ', 1))
  229. if parent is not None:
  230. parent.append(res)
  231. return res
  232. @converter(NavigableString)
  233. def convert_text(bs_node, parent):
  234. if parent is not None:
  235. append_text(parent, unescape(bs_node))
  236. return None
  237. return convert_node
  238. # copied from ET's ElementSoup
  239. try:
  240. from html.entities import name2codepoint # Python 3
  241. except ImportError:
  242. from htmlentitydefs import name2codepoint
  243. handle_entities = re.compile(r"&(\w+);").sub
  244. try:
  245. unichr
  246. except NameError:
  247. # Python 3
  248. unichr = chr
  249. def unescape(string):
  250. if not string:
  251. return ''
  252. # work around oddities in BeautifulSoup's entity handling
  253. def unescape_entity(m):
  254. try:
  255. return unichr(name2codepoint[m.group(1)])
  256. except KeyError:
  257. return m.group(0) # use as is
  258. return handle_entities(unescape_entity, string)