html.py 38 KB

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