html.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  1. """
  2. :mod:`pandas.io.html` is a module containing functionality for dealing with
  3. HTML IO.
  4. """
  5. from collections import abc
  6. import numbers
  7. import os
  8. import re
  9. from pandas.compat._optional import import_optional_dependency
  10. from pandas.errors import AbstractMethodError, EmptyDataError
  11. from pandas.core.dtypes.common import is_list_like
  12. from pandas.core.construction import create_series_with_explicit_dtype
  13. from pandas.io.common import is_url, urlopen, validate_header_arg
  14. from pandas.io.formats.printing import pprint_thing
  15. from pandas.io.parsers import TextParser
  16. _IMPORTS = False
  17. _HAS_BS4 = False
  18. _HAS_LXML = False
  19. _HAS_HTML5LIB = False
  20. def _importers():
  21. # import things we need
  22. # but make this done on a first use basis
  23. global _IMPORTS
  24. if _IMPORTS:
  25. return
  26. global _HAS_BS4, _HAS_LXML, _HAS_HTML5LIB
  27. bs4 = import_optional_dependency("bs4", raise_on_missing=False, on_version="ignore")
  28. _HAS_BS4 = bs4 is not None
  29. lxml = import_optional_dependency(
  30. "lxml.etree", raise_on_missing=False, on_version="ignore"
  31. )
  32. _HAS_LXML = lxml is not None
  33. html5lib = import_optional_dependency(
  34. "html5lib", raise_on_missing=False, on_version="ignore"
  35. )
  36. _HAS_HTML5LIB = html5lib is not None
  37. _IMPORTS = True
  38. #############
  39. # READ HTML #
  40. #############
  41. _RE_WHITESPACE = re.compile(r"[\r\n]+|\s{2,}")
  42. def _remove_whitespace(s: str, regex=_RE_WHITESPACE) -> str:
  43. """
  44. Replace extra whitespace inside of a string with a single space.
  45. Parameters
  46. ----------
  47. s : str or unicode
  48. The string from which to remove extra whitespace.
  49. regex : re.Pattern
  50. The regular expression to use to remove extra whitespace.
  51. Returns
  52. -------
  53. subd : str or unicode
  54. `s` with all extra whitespace replaced with a single space.
  55. """
  56. return regex.sub(" ", s.strip())
  57. def _get_skiprows(skiprows):
  58. """
  59. Get an iterator given an integer, slice or container.
  60. Parameters
  61. ----------
  62. skiprows : int, slice, container
  63. The iterator to use to skip rows; can also be a slice.
  64. Raises
  65. ------
  66. TypeError
  67. * If `skiprows` is not a slice, integer, or Container
  68. Returns
  69. -------
  70. it : iterable
  71. A proper iterator to use to skip rows of a DataFrame.
  72. """
  73. if isinstance(skiprows, slice):
  74. start, step = skiprows.start or 0, skiprows.step or 1
  75. return list(range(start, skiprows.stop, step))
  76. elif isinstance(skiprows, numbers.Integral) or is_list_like(skiprows):
  77. return skiprows
  78. elif skiprows is None:
  79. return 0
  80. raise TypeError(f"{type(skiprows).__name__} is not a valid type for skipping rows")
  81. def _read(obj):
  82. """
  83. Try to read from a url, file or string.
  84. Parameters
  85. ----------
  86. obj : str, unicode, or file-like
  87. Returns
  88. -------
  89. raw_text : str
  90. """
  91. if is_url(obj):
  92. with urlopen(obj) as url:
  93. text = url.read()
  94. elif hasattr(obj, "read"):
  95. text = obj.read()
  96. elif isinstance(obj, (str, bytes)):
  97. text = obj
  98. try:
  99. if os.path.isfile(text):
  100. with open(text, "rb") as f:
  101. return f.read()
  102. except (TypeError, ValueError):
  103. pass
  104. else:
  105. raise TypeError(f"Cannot read object of type '{type(obj).__name__}'")
  106. return text
  107. class _HtmlFrameParser:
  108. """
  109. Base class for parsers that parse HTML into DataFrames.
  110. Parameters
  111. ----------
  112. io : str or file-like
  113. This can be either a string of raw HTML, a valid URL using the HTTP,
  114. FTP, or FILE protocols or a file-like object.
  115. match : str or regex
  116. The text to match in the document.
  117. attrs : dict
  118. List of HTML <table> element attributes to match.
  119. encoding : str
  120. Encoding to be used by parser
  121. displayed_only : bool
  122. Whether or not items with "display:none" should be ignored
  123. .. versionadded:: 0.23.0
  124. Attributes
  125. ----------
  126. io : str or file-like
  127. raw HTML, URL, or file-like object
  128. match : regex
  129. The text to match in the raw HTML
  130. attrs : dict-like
  131. A dictionary of valid table attributes to use to search for table
  132. elements.
  133. encoding : str
  134. Encoding to be used by parser
  135. displayed_only : bool
  136. Whether or not items with "display:none" should be ignored
  137. .. versionadded:: 0.23.0
  138. Notes
  139. -----
  140. To subclass this class effectively you must override the following methods:
  141. * :func:`_build_doc`
  142. * :func:`_attr_getter`
  143. * :func:`_text_getter`
  144. * :func:`_parse_td`
  145. * :func:`_parse_thead_tr`
  146. * :func:`_parse_tbody_tr`
  147. * :func:`_parse_tfoot_tr`
  148. * :func:`_parse_tables`
  149. * :func:`_equals_tag`
  150. See each method's respective documentation for details on their
  151. functionality.
  152. """
  153. def __init__(self, io, match, attrs, encoding, displayed_only):
  154. self.io = io
  155. self.match = match
  156. self.attrs = attrs
  157. self.encoding = encoding
  158. self.displayed_only = displayed_only
  159. def parse_tables(self):
  160. """
  161. Parse and return all tables from the DOM.
  162. Returns
  163. -------
  164. list of parsed (header, body, footer) tuples from tables.
  165. """
  166. tables = self._parse_tables(self._build_doc(), self.match, self.attrs)
  167. return (self._parse_thead_tbody_tfoot(table) for table in tables)
  168. def _attr_getter(self, obj, attr):
  169. """
  170. Return the attribute value of an individual DOM node.
  171. Parameters
  172. ----------
  173. obj : node-like
  174. A DOM node.
  175. attr : str or unicode
  176. The attribute, such as "colspan"
  177. Returns
  178. -------
  179. str or unicode
  180. The attribute value.
  181. """
  182. # Both lxml and BeautifulSoup have the same implementation:
  183. return obj.get(attr)
  184. def _text_getter(self, obj):
  185. """
  186. Return the text of an individual DOM node.
  187. Parameters
  188. ----------
  189. obj : node-like
  190. A DOM node.
  191. Returns
  192. -------
  193. text : str or unicode
  194. The text from an individual DOM node.
  195. """
  196. raise AbstractMethodError(self)
  197. def _parse_td(self, obj):
  198. """
  199. Return the td elements from a row element.
  200. Parameters
  201. ----------
  202. obj : node-like
  203. A DOM <tr> node.
  204. Returns
  205. -------
  206. list of node-like
  207. These are the elements of each row, i.e., the columns.
  208. """
  209. raise AbstractMethodError(self)
  210. def _parse_thead_tr(self, table):
  211. """
  212. Return the list of thead row elements from the parsed table element.
  213. Parameters
  214. ----------
  215. table : a table element that contains zero or more thead elements.
  216. Returns
  217. -------
  218. list of node-like
  219. These are the <tr> row elements of a table.
  220. """
  221. raise AbstractMethodError(self)
  222. def _parse_tbody_tr(self, table):
  223. """
  224. Return the list of tbody row elements from the parsed table element.
  225. HTML5 table bodies consist of either 0 or more <tbody> elements (which
  226. only contain <tr> elements) or 0 or more <tr> elements. This method
  227. checks for both structures.
  228. Parameters
  229. ----------
  230. table : a table element that contains row elements.
  231. Returns
  232. -------
  233. list of node-like
  234. These are the <tr> row elements of a table.
  235. """
  236. raise AbstractMethodError(self)
  237. def _parse_tfoot_tr(self, table):
  238. """
  239. Return the list of tfoot row elements from the parsed table element.
  240. Parameters
  241. ----------
  242. table : a table element that contains row elements.
  243. Returns
  244. -------
  245. list of node-like
  246. These are the <tr> row elements of a table.
  247. """
  248. raise AbstractMethodError(self)
  249. def _parse_tables(self, doc, match, attrs):
  250. """
  251. Return all tables from the parsed DOM.
  252. Parameters
  253. ----------
  254. doc : the DOM from which to parse the table element.
  255. match : str or regular expression
  256. The text to search for in the DOM tree.
  257. attrs : dict
  258. A dictionary of table attributes that can be used to disambiguate
  259. multiple tables on a page.
  260. Raises
  261. ------
  262. ValueError : `match` does not match any text in the document.
  263. Returns
  264. -------
  265. list of node-like
  266. HTML <table> elements to be parsed into raw data.
  267. """
  268. raise AbstractMethodError(self)
  269. def _equals_tag(self, obj, tag):
  270. """
  271. Return whether an individual DOM node matches a tag
  272. Parameters
  273. ----------
  274. obj : node-like
  275. A DOM node.
  276. tag : str
  277. Tag name to be checked for equality.
  278. Returns
  279. -------
  280. boolean
  281. Whether `obj`'s tag name is `tag`
  282. """
  283. raise AbstractMethodError(self)
  284. def _build_doc(self):
  285. """
  286. Return a tree-like object that can be used to iterate over the DOM.
  287. Returns
  288. -------
  289. node-like
  290. The DOM from which to parse the table element.
  291. """
  292. raise AbstractMethodError(self)
  293. def _parse_thead_tbody_tfoot(self, table_html):
  294. """
  295. Given a table, return parsed header, body, and foot.
  296. Parameters
  297. ----------
  298. table_html : node-like
  299. Returns
  300. -------
  301. tuple of (header, body, footer), each a list of list-of-text rows.
  302. Notes
  303. -----
  304. Header and body are lists-of-lists. Top level list is a list of
  305. rows. Each row is a list of str text.
  306. Logic: Use <thead>, <tbody>, <tfoot> elements to identify
  307. header, body, and footer, otherwise:
  308. - Put all rows into body
  309. - Move rows from top of body to header only if
  310. all elements inside row are <th>
  311. - Move rows from bottom of body to footer only if
  312. all elements inside row are <th>
  313. """
  314. header_rows = self._parse_thead_tr(table_html)
  315. body_rows = self._parse_tbody_tr(table_html)
  316. footer_rows = self._parse_tfoot_tr(table_html)
  317. def row_is_all_th(row):
  318. return all(self._equals_tag(t, "th") for t in self._parse_td(row))
  319. if not header_rows:
  320. # The table has no <thead>. Move the top all-<th> rows from
  321. # body_rows to header_rows. (This is a common case because many
  322. # tables in the wild have no <thead> or <tfoot>
  323. while body_rows and row_is_all_th(body_rows[0]):
  324. header_rows.append(body_rows.pop(0))
  325. header = self._expand_colspan_rowspan(header_rows)
  326. body = self._expand_colspan_rowspan(body_rows)
  327. footer = self._expand_colspan_rowspan(footer_rows)
  328. return header, body, footer
  329. def _expand_colspan_rowspan(self, rows):
  330. """
  331. Given a list of <tr>s, return a list of text rows.
  332. Parameters
  333. ----------
  334. rows : list of node-like
  335. List of <tr>s
  336. Returns
  337. -------
  338. list of list
  339. Each returned row is a list of str text.
  340. Notes
  341. -----
  342. Any cell with ``rowspan`` or ``colspan`` will have its contents copied
  343. to subsequent cells.
  344. """
  345. all_texts = [] # list of rows, each a list of str
  346. remainder = [] # list of (index, text, nrows)
  347. for tr in rows:
  348. texts = [] # the output for this row
  349. next_remainder = []
  350. index = 0
  351. tds = self._parse_td(tr)
  352. for td in tds:
  353. # Append texts from previous rows with rowspan>1 that come
  354. # before this <td>
  355. while remainder and remainder[0][0] <= index:
  356. prev_i, prev_text, prev_rowspan = remainder.pop(0)
  357. texts.append(prev_text)
  358. if prev_rowspan > 1:
  359. next_remainder.append((prev_i, prev_text, prev_rowspan - 1))
  360. index += 1
  361. # Append the text from this <td>, colspan times
  362. text = _remove_whitespace(self._text_getter(td))
  363. rowspan = int(self._attr_getter(td, "rowspan") or 1)
  364. colspan = int(self._attr_getter(td, "colspan") or 1)
  365. for _ in range(colspan):
  366. texts.append(text)
  367. if rowspan > 1:
  368. next_remainder.append((index, text, rowspan - 1))
  369. index += 1
  370. # Append texts from previous rows at the final position
  371. for prev_i, prev_text, prev_rowspan in remainder:
  372. texts.append(prev_text)
  373. if prev_rowspan > 1:
  374. next_remainder.append((prev_i, prev_text, prev_rowspan - 1))
  375. all_texts.append(texts)
  376. remainder = next_remainder
  377. # Append rows that only appear because the previous row had non-1
  378. # rowspan
  379. while remainder:
  380. next_remainder = []
  381. texts = []
  382. for prev_i, prev_text, prev_rowspan in remainder:
  383. texts.append(prev_text)
  384. if prev_rowspan > 1:
  385. next_remainder.append((prev_i, prev_text, prev_rowspan - 1))
  386. all_texts.append(texts)
  387. remainder = next_remainder
  388. return all_texts
  389. def _handle_hidden_tables(self, tbl_list, attr_name):
  390. """
  391. Return list of tables, potentially removing hidden elements
  392. Parameters
  393. ----------
  394. tbl_list : list of node-like
  395. Type of list elements will vary depending upon parser used
  396. attr_name : str
  397. Name of the accessor for retrieving HTML attributes
  398. Returns
  399. -------
  400. list of node-like
  401. Return type matches `tbl_list`
  402. """
  403. if not self.displayed_only:
  404. return tbl_list
  405. return [
  406. x
  407. for x in tbl_list
  408. if "display:none"
  409. not in getattr(x, attr_name).get("style", "").replace(" ", "")
  410. ]
  411. class _BeautifulSoupHtml5LibFrameParser(_HtmlFrameParser):
  412. """
  413. HTML to DataFrame parser that uses BeautifulSoup under the hood.
  414. See Also
  415. --------
  416. pandas.io.html._HtmlFrameParser
  417. pandas.io.html._LxmlFrameParser
  418. Notes
  419. -----
  420. Documentation strings for this class are in the base class
  421. :class:`pandas.io.html._HtmlFrameParser`.
  422. """
  423. def __init__(self, *args, **kwargs):
  424. super().__init__(*args, **kwargs)
  425. from bs4 import SoupStrainer
  426. self._strainer = SoupStrainer("table")
  427. def _parse_tables(self, doc, match, attrs):
  428. element_name = self._strainer.name
  429. tables = doc.find_all(element_name, attrs=attrs)
  430. if not tables:
  431. raise ValueError("No tables found")
  432. result = []
  433. unique_tables = set()
  434. tables = self._handle_hidden_tables(tables, "attrs")
  435. for table in tables:
  436. if self.displayed_only:
  437. for elem in table.find_all(style=re.compile(r"display:\s*none")):
  438. elem.decompose()
  439. if table not in unique_tables and table.find(text=match) is not None:
  440. result.append(table)
  441. unique_tables.add(table)
  442. if not result:
  443. raise ValueError(f"No tables found matching pattern {repr(match.pattern)}")
  444. return result
  445. def _text_getter(self, obj):
  446. return obj.text
  447. def _equals_tag(self, obj, tag):
  448. return obj.name == tag
  449. def _parse_td(self, row):
  450. return row.find_all(("td", "th"), recursive=False)
  451. def _parse_thead_tr(self, table):
  452. return table.select("thead tr")
  453. def _parse_tbody_tr(self, table):
  454. from_tbody = table.select("tbody tr")
  455. from_root = table.find_all("tr", recursive=False)
  456. # HTML spec: at most one of these lists has content
  457. return from_tbody + from_root
  458. def _parse_tfoot_tr(self, table):
  459. return table.select("tfoot tr")
  460. def _setup_build_doc(self):
  461. raw_text = _read(self.io)
  462. if not raw_text:
  463. raise ValueError(f"No text parsed from document: {self.io}")
  464. return raw_text
  465. def _build_doc(self):
  466. from bs4 import BeautifulSoup
  467. bdoc = self._setup_build_doc()
  468. if isinstance(bdoc, bytes) and self.encoding is not None:
  469. udoc = bdoc.decode(self.encoding)
  470. from_encoding = None
  471. else:
  472. udoc = bdoc
  473. from_encoding = self.encoding
  474. return BeautifulSoup(udoc, features="html5lib", from_encoding=from_encoding)
  475. def _build_xpath_expr(attrs) -> str:
  476. """Build an xpath expression to simulate bs4's ability to pass in kwargs to
  477. search for attributes when using the lxml parser.
  478. Parameters
  479. ----------
  480. attrs : dict
  481. A dict of HTML attributes. These are NOT checked for validity.
  482. Returns
  483. -------
  484. expr : unicode
  485. An XPath expression that checks for the given HTML attributes.
  486. """
  487. # give class attribute as class_ because class is a python keyword
  488. if "class_" in attrs:
  489. attrs["class"] = attrs.pop("class_")
  490. s = " and ".join([f"@{k}={repr(v)}" for k, v in attrs.items()])
  491. return f"[{s}]"
  492. _re_namespace = {"re": "http://exslt.org/regular-expressions"}
  493. _valid_schemes = "http", "file", "ftp"
  494. class _LxmlFrameParser(_HtmlFrameParser):
  495. """
  496. HTML to DataFrame parser that uses lxml under the hood.
  497. Warning
  498. -------
  499. This parser can only handle HTTP, FTP, and FILE urls.
  500. See Also
  501. --------
  502. _HtmlFrameParser
  503. _BeautifulSoupLxmlFrameParser
  504. Notes
  505. -----
  506. Documentation strings for this class are in the base class
  507. :class:`_HtmlFrameParser`.
  508. """
  509. def __init__(self, *args, **kwargs):
  510. super().__init__(*args, **kwargs)
  511. def _text_getter(self, obj):
  512. return obj.text_content()
  513. def _parse_td(self, row):
  514. # Look for direct children only: the "row" element here may be a
  515. # <thead> or <tfoot> (see _parse_thead_tr).
  516. return row.xpath("./td|./th")
  517. def _parse_tables(self, doc, match, kwargs):
  518. pattern = match.pattern
  519. # 1. check all descendants for the given pattern and only search tables
  520. # 2. go up the tree until we find a table
  521. xpath_expr = f"//table//*[re:test(text(), {repr(pattern)})]/ancestor::table"
  522. # if any table attributes were given build an xpath expression to
  523. # search for them
  524. if kwargs:
  525. xpath_expr += _build_xpath_expr(kwargs)
  526. tables = doc.xpath(xpath_expr, namespaces=_re_namespace)
  527. tables = self._handle_hidden_tables(tables, "attrib")
  528. if self.displayed_only:
  529. for table in tables:
  530. # lxml utilizes XPATH 1.0 which does not have regex
  531. # support. As a result, we find all elements with a style
  532. # attribute and iterate them to check for display:none
  533. for elem in table.xpath(".//*[@style]"):
  534. if "display:none" in elem.attrib.get("style", "").replace(" ", ""):
  535. elem.getparent().remove(elem)
  536. if not tables:
  537. raise ValueError(f"No tables found matching regex {repr(pattern)}")
  538. return tables
  539. def _equals_tag(self, obj, tag):
  540. return obj.tag == tag
  541. def _build_doc(self):
  542. """
  543. Raises
  544. ------
  545. ValueError
  546. * If a URL that lxml cannot parse is passed.
  547. Exception
  548. * Any other ``Exception`` thrown. For example, trying to parse a
  549. URL that is syntactically correct on a machine with no internet
  550. connection will fail.
  551. See Also
  552. --------
  553. pandas.io.html._HtmlFrameParser._build_doc
  554. """
  555. from lxml.html import parse, fromstring, HTMLParser
  556. from lxml.etree import XMLSyntaxError
  557. parser = HTMLParser(recover=True, encoding=self.encoding)
  558. try:
  559. if is_url(self.io):
  560. with urlopen(self.io) as f:
  561. r = parse(f, parser=parser)
  562. else:
  563. # try to parse the input in the simplest way
  564. r = parse(self.io, parser=parser)
  565. try:
  566. r = r.getroot()
  567. except AttributeError:
  568. pass
  569. except (UnicodeDecodeError, IOError) as e:
  570. # if the input is a blob of html goop
  571. if not is_url(self.io):
  572. r = fromstring(self.io, parser=parser)
  573. try:
  574. r = r.getroot()
  575. except AttributeError:
  576. pass
  577. else:
  578. raise e
  579. else:
  580. if not hasattr(r, "text_content"):
  581. raise XMLSyntaxError("no text parsed from document", 0, 0, 0)
  582. return r
  583. def _parse_thead_tr(self, table):
  584. rows = []
  585. for thead in table.xpath(".//thead"):
  586. rows.extend(thead.xpath("./tr"))
  587. # HACK: lxml does not clean up the clearly-erroneous
  588. # <thead><th>foo</th><th>bar</th></thead>. (Missing <tr>). Add
  589. # the <thead> and _pretend_ it's a <tr>; _parse_td() will find its
  590. # children as though it's a <tr>.
  591. #
  592. # Better solution would be to use html5lib.
  593. elements_at_root = thead.xpath("./td|./th")
  594. if elements_at_root:
  595. rows.append(thead)
  596. return rows
  597. def _parse_tbody_tr(self, table):
  598. from_tbody = table.xpath(".//tbody//tr")
  599. from_root = table.xpath("./tr")
  600. # HTML spec: at most one of these lists has content
  601. return from_tbody + from_root
  602. def _parse_tfoot_tr(self, table):
  603. return table.xpath(".//tfoot//tr")
  604. def _expand_elements(body):
  605. data = [len(elem) for elem in body]
  606. lens = create_series_with_explicit_dtype(data, dtype_if_empty=object)
  607. lens_max = lens.max()
  608. not_max = lens[lens != lens_max]
  609. empty = [""]
  610. for ind, length in not_max.items():
  611. body[ind] += empty * (lens_max - length)
  612. def _data_to_frame(**kwargs):
  613. head, body, foot = kwargs.pop("data")
  614. header = kwargs.pop("header")
  615. kwargs["skiprows"] = _get_skiprows(kwargs["skiprows"])
  616. if head:
  617. body = head + body
  618. # Infer header when there is a <thead> or top <th>-only rows
  619. if header is None:
  620. if len(head) == 1:
  621. header = 0
  622. else:
  623. # ignore all-empty-text rows
  624. header = [i for i, row in enumerate(head) if any(text for text in row)]
  625. if foot:
  626. body += foot
  627. # fill out elements of body that are "ragged"
  628. _expand_elements(body)
  629. tp = TextParser(body, header=header, **kwargs)
  630. df = tp.read()
  631. return df
  632. _valid_parsers = {
  633. "lxml": _LxmlFrameParser,
  634. None: _LxmlFrameParser,
  635. "html5lib": _BeautifulSoupHtml5LibFrameParser,
  636. "bs4": _BeautifulSoupHtml5LibFrameParser,
  637. }
  638. def _parser_dispatch(flavor):
  639. """
  640. Choose the parser based on the input flavor.
  641. Parameters
  642. ----------
  643. flavor : str
  644. The type of parser to use. This must be a valid backend.
  645. Returns
  646. -------
  647. cls : _HtmlFrameParser subclass
  648. The parser class based on the requested input flavor.
  649. Raises
  650. ------
  651. ValueError
  652. * If `flavor` is not a valid backend.
  653. ImportError
  654. * If you do not have the requested `flavor`
  655. """
  656. valid_parsers = list(_valid_parsers.keys())
  657. if flavor not in valid_parsers:
  658. raise ValueError(
  659. f"{repr(flavor)} is not a valid flavor, valid flavors are {valid_parsers}"
  660. )
  661. if flavor in ("bs4", "html5lib"):
  662. if not _HAS_HTML5LIB:
  663. raise ImportError("html5lib not found, please install it")
  664. if not _HAS_BS4:
  665. raise ImportError("BeautifulSoup4 (bs4) not found, please install it")
  666. # Although we call this above, we want to raise here right before use.
  667. bs4 = import_optional_dependency("bs4") # noqa:F841
  668. else:
  669. if not _HAS_LXML:
  670. raise ImportError("lxml not found, please install it")
  671. return _valid_parsers[flavor]
  672. def _print_as_set(s) -> str:
  673. arg = ", ".join(pprint_thing(el) for el in s)
  674. return f"{{{arg}}}"
  675. def _validate_flavor(flavor):
  676. if flavor is None:
  677. flavor = "lxml", "bs4"
  678. elif isinstance(flavor, str):
  679. flavor = (flavor,)
  680. elif isinstance(flavor, abc.Iterable):
  681. if not all(isinstance(flav, str) for flav in flavor):
  682. raise TypeError(
  683. f"Object of type {repr(type(flavor).__name__)} "
  684. f"is not an iterable of strings"
  685. )
  686. else:
  687. msg = repr(flavor) if isinstance(flavor, str) else str(flavor)
  688. msg += " is not a valid flavor"
  689. raise ValueError(msg)
  690. flavor = tuple(flavor)
  691. valid_flavors = set(_valid_parsers)
  692. flavor_set = set(flavor)
  693. if not flavor_set & valid_flavors:
  694. raise ValueError(
  695. f"{_print_as_set(flavor_set)} is not a valid set of flavors, valid "
  696. f"flavors are {_print_as_set(valid_flavors)}"
  697. )
  698. return flavor
  699. def _parse(flavor, io, match, attrs, encoding, displayed_only, **kwargs):
  700. flavor = _validate_flavor(flavor)
  701. compiled_match = re.compile(match) # you can pass a compiled regex here
  702. retained = None
  703. for flav in flavor:
  704. parser = _parser_dispatch(flav)
  705. p = parser(io, compiled_match, attrs, encoding, displayed_only)
  706. try:
  707. tables = p.parse_tables()
  708. except ValueError as caught:
  709. # if `io` is an io-like object, check if it's seekable
  710. # and try to rewind it before trying the next parser
  711. if hasattr(io, "seekable") and io.seekable():
  712. io.seek(0)
  713. elif hasattr(io, "seekable") and not io.seekable():
  714. # if we couldn't rewind it, let the user know
  715. raise ValueError(
  716. f"The flavor {flav} failed to parse your input. "
  717. "Since you passed a non-rewindable file "
  718. "object, we can't rewind it to try "
  719. "another parser. Try read_html() with a "
  720. "different flavor."
  721. )
  722. retained = caught
  723. else:
  724. break
  725. else:
  726. raise retained
  727. ret = []
  728. for table in tables:
  729. try:
  730. ret.append(_data_to_frame(data=table, **kwargs))
  731. except EmptyDataError: # empty table
  732. continue
  733. return ret
  734. def read_html(
  735. io,
  736. match=".+",
  737. flavor=None,
  738. header=None,
  739. index_col=None,
  740. skiprows=None,
  741. attrs=None,
  742. parse_dates=False,
  743. thousands=",",
  744. encoding=None,
  745. decimal=".",
  746. converters=None,
  747. na_values=None,
  748. keep_default_na=True,
  749. displayed_only=True,
  750. ):
  751. r"""
  752. Read HTML tables into a ``list`` of ``DataFrame`` objects.
  753. Parameters
  754. ----------
  755. io : str, path object or file-like object
  756. A URL, a file-like object, or a raw string containing HTML. Note that
  757. lxml only accepts the http, ftp and file url protocols. If you have a
  758. URL that starts with ``'https'`` you might try removing the ``'s'``.
  759. match : str or compiled regular expression, optional
  760. The set of tables containing text matching this regex or string will be
  761. returned. Unless the HTML is extremely simple you will probably need to
  762. pass a non-empty string here. Defaults to '.+' (match any non-empty
  763. string). The default value will return all tables contained on a page.
  764. This value is converted to a regular expression so that there is
  765. consistent behavior between Beautiful Soup and lxml.
  766. flavor : str or None
  767. The parsing engine to use. 'bs4' and 'html5lib' are synonymous with
  768. each other, they are both there for backwards compatibility. The
  769. default of ``None`` tries to use ``lxml`` to parse and if that fails it
  770. falls back on ``bs4`` + ``html5lib``.
  771. header : int or list-like or None, optional
  772. The row (or list of rows for a :class:`~pandas.MultiIndex`) to use to
  773. make the columns headers.
  774. index_col : int or list-like or None, optional
  775. The column (or list of columns) to use to create the index.
  776. skiprows : int or list-like or slice or None, optional
  777. Number of rows to skip after parsing the column integer. 0-based. If a
  778. sequence of integers or a slice is given, will skip the rows indexed by
  779. that sequence. Note that a single element sequence means 'skip the nth
  780. row' whereas an integer means 'skip n rows'.
  781. attrs : dict or None, optional
  782. This is a dictionary of attributes that you can pass to use to identify
  783. the table in the HTML. These are not checked for validity before being
  784. passed to lxml or Beautiful Soup. However, these attributes must be
  785. valid HTML table attributes to work correctly. For example, ::
  786. attrs = {'id': 'table'}
  787. is a valid attribute dictionary because the 'id' HTML tag attribute is
  788. a valid HTML attribute for *any* HTML tag as per `this document
  789. <http://www.w3.org/TR/html-markup/global-attributes.html>`__. ::
  790. attrs = {'asdf': 'table'}
  791. is *not* a valid attribute dictionary because 'asdf' is not a valid
  792. HTML attribute even if it is a valid XML attribute. Valid HTML 4.01
  793. table attributes can be found `here
  794. <http://www.w3.org/TR/REC-html40/struct/tables.html#h-11.2>`__. A
  795. working draft of the HTML 5 spec can be found `here
  796. <http://www.w3.org/TR/html-markup/table.html>`__. It contains the
  797. latest information on table attributes for the modern web.
  798. parse_dates : bool, optional
  799. See :func:`~read_csv` for more details.
  800. thousands : str, optional
  801. Separator to use to parse thousands. Defaults to ``','``.
  802. encoding : str or None, optional
  803. The encoding used to decode the web page. Defaults to ``None``.``None``
  804. preserves the previous encoding behavior, which depends on the
  805. underlying parser library (e.g., the parser library will try to use
  806. the encoding provided by the document).
  807. decimal : str, default '.'
  808. Character to recognize as decimal point (e.g. use ',' for European
  809. data).
  810. converters : dict, default None
  811. Dict of functions for converting values in certain columns. Keys can
  812. either be integers or column labels, values are functions that take one
  813. input argument, the cell (not column) content, and return the
  814. transformed content.
  815. na_values : iterable, default None
  816. Custom NA values.
  817. keep_default_na : bool, default True
  818. If na_values are specified and keep_default_na is False the default NaN
  819. values are overridden, otherwise they're appended to.
  820. displayed_only : bool, default True
  821. Whether elements with "display: none" should be parsed.
  822. Returns
  823. -------
  824. dfs
  825. A list of DataFrames.
  826. See Also
  827. --------
  828. read_csv
  829. Notes
  830. -----
  831. Before using this function you should read the :ref:`gotchas about the
  832. HTML parsing libraries <io.html.gotchas>`.
  833. Expect to do some cleanup after you call this function. For example, you
  834. might need to manually assign column names if the column names are
  835. converted to NaN when you pass the `header=0` argument. We try to assume as
  836. little as possible about the structure of the table and push the
  837. idiosyncrasies of the HTML contained in the table to the user.
  838. This function searches for ``<table>`` elements and only for ``<tr>``
  839. and ``<th>`` rows and ``<td>`` elements within each ``<tr>`` or ``<th>``
  840. element in the table. ``<td>`` stands for "table data". This function
  841. attempts to properly handle ``colspan`` and ``rowspan`` attributes.
  842. If the function has a ``<thead>`` argument, it is used to construct
  843. the header, otherwise the function attempts to find the header within
  844. the body (by putting rows with only ``<th>`` elements into the header).
  845. .. versionadded:: 0.21.0
  846. Similar to :func:`~read_csv` the `header` argument is applied
  847. **after** `skiprows` is applied.
  848. This function will *always* return a list of :class:`DataFrame` *or*
  849. it will fail, e.g., it will *not* return an empty list.
  850. Examples
  851. --------
  852. See the :ref:`read_html documentation in the IO section of the docs
  853. <io.read_html>` for some examples of reading in HTML tables.
  854. """
  855. _importers()
  856. # Type check here. We don't want to parse only to fail because of an
  857. # invalid value of an integer skiprows.
  858. if isinstance(skiprows, numbers.Integral) and skiprows < 0:
  859. raise ValueError(
  860. "cannot skip rows starting from the end of the "
  861. "data (you passed a negative value)"
  862. )
  863. validate_header_arg(header)
  864. return _parse(
  865. flavor=flavor,
  866. io=io,
  867. match=match,
  868. header=header,
  869. index_col=index_col,
  870. skiprows=skiprows,
  871. parse_dates=parse_dates,
  872. thousands=thousands,
  873. attrs=attrs,
  874. encoding=encoding,
  875. decimal=decimal,
  876. converters=converters,
  877. na_values=na_values,
  878. keep_default_na=keep_default_na,
  879. displayed_only=displayed_only,
  880. )