html.py 39 KB

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