gL izdZddlmZddlmZddlZddlZddlmZddlm Z m Z m Z ddl Z ddl mZddlmZdd lmZmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddl m!Z!ddl"m#Z#ddl$m%Z%ddl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-ddl.m/Z/ddl0m1Z1e rddl2m3Z3m4Z4ddl5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;ddlme>fd6dZ?d7dZ@ d8dZAGddZBGd d!eBZCd9d"ZDd#d$iZEGd%d&eBZFd:d'ZGd(ZHeFeFeCeCd)ZId;d*ZJd9d+ZKd,ZLd-ZMee%d.d/dddddd0d1dd2ddd3d3dejdd4 dr?r@)objrGrChandlestexts r/_readrPys$ s 3  sC [%5  x  ) >>&&(D ) K C#u & K6tCy7I7I6J!LMM ) Ks B##B-ceZdZdZ d ddZdZdZddZdZdZ d Z d Z d Z d Z dd ZdZdZ ddZddZy)_HtmlFrameParseraZ Base class for parsers that parse HTML into DataFrames. Parameters ---------- io : str or file-like This can be either a string of raw HTML, a valid URL using the HTTP, FTP, or FILE protocols or a file-like object. match : str or regex The text to match in the document. attrs : dict List of HTML element attributes to match. encoding : str Encoding to be used by parser displayed_only : bool Whether or not items with "display:none" should be ignored extract_links : {None, "all", "header", "body", "footer"} Table elements in the specified section(s) with tags will have their href extracted. .. versionadded:: 1.5.0 Attributes ---------- io : str or file-like raw HTML, URL, or file-like object match : regex The text to match in the raw HTML attrs : dict-like A dictionary of valid table attributes to use to search for table elements. encoding : str Encoding to be used by parser displayed_only : bool Whether or not items with "display:none" should be ignored extract_links : {None, "all", "header", "body", "footer"} Table elements in the specified section(s) with tags will have their href extracted. .. versionadded:: 1.5.0 Notes ----- To subclass this class effectively you must override the following methods: * :func:`_build_doc` * :func:`_attr_getter` * :func:`_href_getter` * :func:`_text_getter` * :func:`_parse_td` * :func:`_parse_thead_tr` * :func:`_parse_tbody_tr` * :func:`_parse_tfoot_tr` * :func:`_parse_tables` * :func:`_equals_tag` See each method's respective documentation for details on their functionality. Ncf||_||_||_||_||_||_||_yN)iomatchattrsrGdisplayed_only extract_linksrC)selfrUrVrWrGrXrYrCs r/__init__z_HtmlFrameParser.__init__s8    ,*.r1cjjjj}fd|DS)z Parse and return all tables from the DOM. Returns ------- list of parsed (header, body, footer) tuples from tables. c3@K|]}j|ywrT)_parse_thead_tbody_tfoot).0tablerZs r/ z0_HtmlFrameParser.parse_tables..sI--e4Is) _parse_tables _build_docrVrW)rZtabless` r/ parse_tablesz_HtmlFrameParser.parse_tabless3##DOO$5tzz4::NI&IIr1c$|j|S)aC Return the attribute value of an individual DOM node. Parameters ---------- obj : node-like A DOM node. attr : str or unicode The attribute, such as "colspan" Returns ------- str or unicode The attribute value. )get)rZrMattrs r/ _attr_getterz_HtmlFrameParser._attr_getters$wwt}r1ct|)a Return a href if the DOM node contains a child or None. Parameters ---------- obj : node-like A DOM node. Returns ------- href : str or unicode The href from the child of the DOM node. r rZrMs r/ _href_getterz_HtmlFrameParser._href_getter"$''r1ct|)a Return the text of an individual DOM node. Parameters ---------- obj : node-like A DOM node. Returns ------- text : str or unicode The text from an individual DOM node. rkrls r/ _text_getterz_HtmlFrameParser._text_getter rnr1ct|)a Return the td elements from a row element. Parameters ---------- obj : node-like A DOM node. Returns ------- list of node-like These are the elements of each row, i.e., the columns. rkrls r/ _parse_tdz_HtmlFrameParser._parse_td0rnr1ct|)a; Return the list of thead row elements from the parsed table element. Parameters ---------- table : a table element that contains zero or more thead elements. Returns ------- list of node-like These are the row elements of a table. rkrZr`s r/_parse_thead_trz _HtmlFrameParser._parse_thead_tr@"$''r1ct|)a Return the list of tbody row elements from the parsed table element. HTML5 table bodies consist of either 0 or more elements (which only contain elements) or 0 or more elements. This method checks for both structures. Parameters ---------- table : a table element that contains row elements. Returns ------- list of node-like These are the row elements of a table. rkrts r/_parse_tbody_trz _HtmlFrameParser._parse_tbody_trO""$''r1ct|)a, Return the list of tfoot row elements from the parsed table element. Parameters ---------- table : a table element that contains row elements. Returns ------- list of node-like These are the row elements of a table. rkrts r/_parse_tfoot_trz _HtmlFrameParser._parse_tfoot_trbrvr1ct|)ai Return all tables from the parsed DOM. Parameters ---------- document : the DOM from which to parse the table element. match : str or regular expression The text to search for in the DOM tree. attrs : dict A dictionary of table attributes that can be used to disambiguate multiple tables on a page. Raises ------ ValueError : `match` does not match any text in the document. Returns ------- list of node-like HTML
elements to be parsed into raw data. rk)rZdocumentrVrWs r/rbz_HtmlFrameParser._parse_tablesqs0"$''r1ct|)a? Return whether an individual DOM node matches a tag Parameters ---------- obj : node-like A DOM node. tag : str Tag name to be checked for equality. Returns ------- boolean Whether `obj`'s tag name is `tag` rkrZrMtags r/ _equals_tagz_HtmlFrameParser._equals_tagryr1ct|)z Return a tree-like object that can be used to iterate over the DOM. Returns ------- node-like The DOM from which to parse the table element. rk)rZs r/rcz_HtmlFrameParser._build_docs"$''r1cjj|}j|}j|}fd}|s;|r9||dr.|j|j d|r ||dr.j |d}j |d}j |d}|||fS)a  Given a table, return parsed header, body, and foot. Parameters ---------- table_html : node-like Returns ------- tuple of (header, body, footer), each a list of list-of-text rows. Notes ----- Header and body are lists-of-lists. Top level list is a list of rows. Each row is a list of str text. Logic: Use , , elements to identify header, body, and footer, otherwise: - Put all rows into body - Move rows from top of body to header only if all elements inside row are s, return a list of text rows. Parameters ---------- rows : list of node-like List of s section : the section that the rows belong to (header, body or footer). Returns ------- list of list Each returned row is a list of str text, or tuple (text, link) if extract_links is not None. Notes ----- Any cell with ``rowspan`` or ``colspan`` will have its contents copied to subsequent cells. rr3rrowspancolspan) rrrrr0rprYrmintrir:)rZrowsr all_texts remaindertrtextsnext_remainderindextdstdprev_i prev_text prev_rowspanrOhrefrr_s r/rz(_HtmlFrameParser._expand_colspan_rowspans^.   % 'BENE..$C  IaLOu$<6?mmA6F3FI|LL+#a'&--vy,QRBR.STQJE  IaLOu$<*$*;*;B*?@%%%)99,,R0D $C!Dd//I>C!DwALL&{&--udGaK.HIQJE % 24= Q/ < Y'!#"))69lQ>N*OP Q   U #&IK% 'RNE3< Q/ < Y'!#"))69lQ>N*OP Q   U #&Ir1c|js|S|Dcgc]2}dt||jddjddvr|4c}Scc}w)a Return list of tables, potentially removing hidden elements Parameters ---------- tbl_list : list of node-like Type of list elements will vary depending upon parser used attr_name : str Name of the accessor for retrieving HTML attributes Returns ------- list of node-like Return type matches `tbl_list` display:nonestyler*)rXgetattrrgreplace)rZtbl_list attr_namexs r/_handle_hidden_tablesz&_HtmlFrameParser._handle_hidden_tables(sa ""O 1i(,,Wb9AA#rJK    s7A rT)rUz.FilePath | ReadBuffer[str] | ReadBuffer[bytes]rV str | PatternrWdict[str, str] | NonerGrJrXboolrY0Literal[None, 'header', 'footer', 'body', 'all']rCr'returnNoner str | Nonerr)rz#Literal['header', 'footer', 'body'])rrJ)r@ __module__ __qualname____doc__r[rerirmrprrrurxr{rbrrcr^rrr1r/rRrRsBX+// ://% /  /  /H/(/ /$ J(( ( ( ((& ((4(& (+$ZP@Pd r1rRcPeZdZdZdZd dZdZddZdZdZ dZ d Z d Z d Z y )!_BeautifulSoupHtml5LibFrameParsera/ HTML to DataFrame parser that uses BeautifulSoup under the hood. See Also -------- pandas.io.html._HtmlFrameParser pandas.io.html._LxmlFrameParser Notes ----- Documentation strings for this class are in the base class :class:`pandas.io.html._HtmlFrameParser`. c"d}|j||}|s tdg}t}|j|d}|D]}|jr`|jdD]} | j |jt jdD]} | j ||vr#|j||j||j||s!td t|j|S) Nr`)rWzNo tables foundrWrzdisplay:\s*none)r)stringz!No tables found matching pattern ) find_all ValueErrorsetrrX decomposerecompilefindraddreprpattern) rZr}rVrW element_namerdresult unique_tablesr`elems r/rbz/_BeautifulSoupHtml5LibFrameParser._parse_tablesRs ""tG}oNO O r1c |j|k(SrT)rrs r/rz_LxmlFrameParser._equals_tagsww#~r1cddlm}ddlm}m}m}|d|j } t|jr@t|jd|j5}||j|}d d d n||j|} j}td s |d ddd|j#d D]} d | j$xsdz| _|S#1swYaxYw#t$rY^wxYw#tt f$rV}t|js5||j|} |j}n#t$rYnwxYw|Yd }~d }~wwxYw)a Raises ------ ValueError * If a URL that lxml cannot parse is passed. Exception * Any other ``Exception`` thrown. For example, trying to parse a URL that is syntactically correct on a machine with no internet connection will fail. See Also -------- pandas.io.html._HtmlFrameParser._build_doc r)XMLSyntaxError) HTMLParser fromstringparseT)recoverrGrFrC)parserNrzno text parsed from documentz*//brrr) lxml.etreer lxml.htmlrrrrGrrUrrCrKgetrootAttributeErrorrIUnicodeDecodeErrorOSErrorrtail) rZrrrrrfrFers r/rcz_LxmlFrameParser._build_docsY .  D4==A NdggGGS$2F2F7ahhv6A77 $''&1 IIK1n-$%CQ1MM'''" -Bbggm,BG -;77"  "G, $''?twwv6 A% sq7DC'2DC3'C0,D3 C?<D>C??DE')E";E  E" EE"EE""E'cg}|jdD]G}|j|jd|jd}|s7|j|I|S)Nz.//thead./trr)rextendr)rZr`rtheadelements_at_roots r/ruz _LxmlFrameParser._parse_thead_tr0s[[[, #E KK F+ , %{{;7  E" # r1cP|jd}|jd}||zS)Nz .//tbody//trr"rrs r/rxz _LxmlFrameParser._parse_tbody_trBs)[[0 KK' I%%r1c$|jdS)Nz .//tfoot//trrrts r/r{z _LxmlFrameParser._parse_tfoot_trHs{{>**r1Nrr) r@rrrrmrprrrbrrcrurxr{rr1r/rrs5$-"& :8t$& +r1rc|Dcgc] }t|}}t|}|j}|||k7}dg}|jD]\}}||xx|||z zz cc<ycc}w)Nr)lenrmaxr) rrdatalenslens_maxnot_maxemptyindlengths r/_expand_elementsr2Lsy"& '$CI 'D ' $.ds@V$@Vs )rrBr) enumerateanyr2rrE)r headrfootrirtps r/_data_to_framer;Wszz&)D$ ZZ !F&vj'9:F: d{ >4yA~+4D/W3S@VRU@V=V!WW   T D 2 26 2bwwyXs B<;B<"CC )lxmlNrrcttj}||vrtt |d||dvrt dt dt|St dt|S)a Choose the parser based on the input flavor. Parameters ---------- flavor : {{"lxml", "html5lib", "bs4"}} or None The type of parser to use. This must be a valid backend. Returns ------- cls : _HtmlFrameParser subclass The parser class based on the requested input flavor. Raises ------ ValueError * If `flavor` is not a valid backend. ImportError * If you do not have the requested `flavor` z* is not a valid flavor, valid flavors are )rrrrz lxml.etree)r9_valid_parserskeysrrr )flavor valid_parserss r/_parser_dispatchrBws|*,,./M ]"F|nF}o V  $$":."5) & !! #<0 & !!r1chdj|Dcgc] }t|c}}d|dScc}w)Nz, {})rr)r-elargs r/ _print_as_setrHs3 ))2"\"%2 3C uB<3s/c|d}nt|tr|f}nt|tjr=t d|Dsat dt t|jdt|tr t |n t|}|dz }t|t|}tt}t|}||zs"tt|dt||S)N)r<rc3<K|]}t|tywrT)r5rJ)r_flavs r/raz#_validate_flavor..srr?r@rtuplerr>rH)r@msg valid_flavors flavor_sets r/_validate_flavorrPs ~ FC  FCLL )?01  )5d6l3v; ''o 6]F'MVJ  %Z()*(78 :   Mr1c t|}tj|} d} |D]-} t| } | || |||||} | j }n| J| g}|D]b} td d|i|}|dvr=t|jtr#td|jDd |_ |j|d|S#t $rg}t |dr"|jr|jdn,t |dr |jst d| d||} Yd}~ d}~wwxYw#t$rYwxYw) Nseekablerz The flavor z failed to parse your input. Since you passed a non-rewindable file object, we can't rewind it to try another parser. Try read_html() with a different flavor.r+)rrc3PK|]}|dt|drdn|df yw)rr3Nr)r_cols r/raz_parse..s)VCc!fd3q6ldA?Vs$&F) tupleize_colsr)rPrrrBrerrIrRseekr;r5columnsrrrr )r@rUrVrWrGrXrYrCr compiled_matchretainedrKrprdcaughtretr`dfs r/_parser^s~f %FZZ&NH!!$'          ^^%F" =!@### C 5U5f5B 11j J7#V2::V"' JJrN" JO r:&2;;= Z( !$(OO  H J   s,C#AD9 D6AD11D69 EErz.+F,.T)rVr@r index_colrArW parse_dates thousandsrGdecimal converters na_valueskeep_default_narXrY dtype_backendrCc t|tjr|dkr td|dvrtd|dt |t |t |}t|trWtt|t|t|t|gs$tjdtt!t#did|d |d |d |d |d |d|d|d|d| d| d| d| d| d|d|d|d|S)a Read HTML tables into a ``list`` of ``DataFrame`` objects. Parameters ---------- io : str, path object, or file-like object String, path object (implementing ``os.PathLike[str]``), or file-like object implementing a string ``read()`` function. The string can represent a URL or the HTML itself. Note that lxml only accepts the http, ftp and file url protocols. If you have a URL that starts with ``'https'`` you might try removing the ``'s'``. .. deprecated:: 2.1.0 Passing html literal strings is deprecated. Wrap literal string/bytes input in ``io.StringIO``/``io.BytesIO`` instead. match : str or compiled regular expression, optional The set of tables containing text matching this regex or string will be returned. Unless the HTML is extremely simple you will probably need to pass a non-empty string here. Defaults to '.+' (match any non-empty string). The default value will return all tables contained on a page. This value is converted to a regular expression so that there is consistent behavior between Beautiful Soup and lxml. flavor : {{"lxml", "html5lib", "bs4"}} or list-like, optional The parsing engine (or list of parsing engines) to use. 'bs4' and 'html5lib' are synonymous with each other, they are both there for backwards compatibility. The default of ``None`` tries to use ``lxml`` to parse and if that fails it falls back on ``bs4`` + ``html5lib``. header : int or list-like, optional The row (or list of rows for a :class:`~pandas.MultiIndex`) to use to make the columns headers. index_col : int or list-like, optional The column (or list of columns) to use to create the index. skiprows : int, list-like or slice, optional Number of rows to skip after parsing the column integer. 0-based. If a sequence of integers or a slice is given, will skip the rows indexed by that sequence. Note that a single element sequence means 'skip the nth row' whereas an integer means 'skip n rows'. attrs : dict, optional This is a dictionary of attributes that you can pass to use to identify the table in the HTML. These are not checked for validity before being passed to lxml or Beautiful Soup. However, these attributes must be valid HTML table attributes to work correctly. For example, :: attrs = {{'id': 'table'}} is a valid attribute dictionary because the 'id' HTML tag attribute is a valid HTML attribute for *any* HTML tag as per `this document `__. :: attrs = {{'asdf': 'table'}} is *not* a valid attribute dictionary because 'asdf' is not a valid HTML attribute even if it is a valid XML attribute. Valid HTML 4.01 table attributes can be found `here `__. A working draft of the HTML 5 spec can be found `here `__. It contains the latest information on table attributes for the modern web. parse_dates : bool, optional See :func:`~read_csv` for more details. thousands : str, optional Separator to use to parse thousands. Defaults to ``','``. encoding : str, optional The encoding used to decode the web page. Defaults to ``None``.``None`` preserves the previous encoding behavior, which depends on the underlying parser library (e.g., the parser library will try to use the encoding provided by the document). decimal : str, default '.' Character to recognize as decimal point (e.g. use ',' for European data). converters : dict, default None Dict of functions for converting values in certain columns. Keys can either be integers or column labels, values are functions that take one input argument, the cell (not column) content, and return the transformed content. na_values : iterable, default None Custom NA values. keep_default_na : bool, default True If na_values are specified and keep_default_na is False the default NaN values are overridden, otherwise they're appended to. displayed_only : bool, default True Whether elements with "display: none" should be parsed. extract_links : {{None, "all", "header", "body", "footer"}} Table elements in the specified section(s) with tags will have their href extracted. .. versionadded:: 1.5.0 dtype_backend : {{'numpy_nullable', 'pyarrow'}}, default 'numpy_nullable' Back-end data type applied to the resultant :class:`DataFrame` (still experimental). Behaviour is as follows: * ``"numpy_nullable"``: returns nullable-dtype-backed :class:`DataFrame` (default). * ``"pyarrow"``: returns pyarrow-backed nullable :class:`ArrowDtype` DataFrame. .. versionadded:: 2.0 {storage_options} .. versionadded:: 2.1.0 Returns ------- dfs A list of DataFrames. See Also -------- read_csv : Read a comma-separated values (csv) file into DataFrame. Notes ----- Before using this function you should read the :ref:`gotchas about the HTML parsing libraries `. Expect to do some cleanup after you call this function. For example, you might need to manually assign column names if the column names are converted to NaN when you pass the `header=0` argument. We try to assume as little as possible about the structure of the table and push the idiosyncrasies of the HTML contained in the table to the user. This function searches for ``
- Move rows from bottom of body to footer only if all elements inside row are cJtfdj|DS)Nc3BK|]}j|dyw)thN)r)r_trZs r/razS_HtmlFrameParser._parse_thead_tbody_tfoot..row_is_all_th..sNQt''40Ns)allrr)rowrZs r/ row_is_all_thz@_HtmlFrameParser._parse_thead_tbody_tfoot..row_is_all_thsN$..:MNN Nr1rheader)sectionbodyfooter)rurxr{appendpop_expand_colspan_rowspan) rZ table_html header_rows body_rows footer_rowsrrrrs ` r/r^z)_HtmlFrameParser._parse_thead_tbody_tfoots2**:6 ((4 **:6  O il ;""9==#34 il ;--k8-L++Iv+F--k8-LtV##r1c g}g}|D]}g}g}d}|j|} | D]$} |r`|dd|krU|jd\} } } |j| | dkDr|j| | | dz f|dz }|r |dd|krUt|j | }|j d|fvr|j | }||f}t|j| dxsd}t|j| dxsd}t|D]4}|j||dkDr|j|||dz f|dz }6'|D]4\} } } |j| | dkDs|j| | | dz f6|j||}|rSg}g}|D]4\} } } |j| | dkDs|j| | | dz f6|j||}|rS|S)a* Given a list of
`` elements and only for ```` and ```` or ```` argument, it is used to construct the header, otherwise the function attempts to find the header within the body (by putting rows with only ``
`` rows and ```` elements within each ``
`` element in the table. ```` stands for "table data". This function attempts to properly handle ``colspan`` and ``rowspan`` attributes. If the function has a ``
`` elements into the header). Similar to :func:`~read_csv` the `header` argument is applied **after** `skiprows` is applied. This function will *always* return a list of :class:`DataFrame` *or* it will fail, e.g., it will *not* return an empty list. Examples -------- See the :ref:`read_html documentation in the IO section of the docs ` for some examples of reading in HTML tables. rzPcannot skip rows starting from the end of the data (you passed a negative value))NrrrrzO`extract_links` must be one of {None, "header", "footer", "body", "all"}, got ""zPassing literal html to 'read_html' is deprecated and will be removed in a future version. To read from a literal string, wrap it in a 'StringIO' object.) stacklevelr@rUrVrrarArbrcrWrGrdrerfrgrXrYrhrCr)r5r<r=rrrrrJr6rrrrwarningswarn FutureWarningrr^)rUrVr@rrarArWrbrcrGrdrerfrgrXrYrhrCs r/ read_htmlrosj(G,,-(Q, 1  EE a !   &  B"c3   O 2J "   $   > ')                        ( &  $! "$# $(% r1)r-rJr.rrrJ)rA"int | Sequence[int] | slice | Nonerr4)rMzFilePath | BaseBufferrGrrCzStorageOptions | Nonerz str | bytes)rrJ)rr)r@zHTMLFlavors | Nonerztype[_HtmlFrameParser])&rUzFilePath | ReadBuffer[str]rVrr@z*HTMLFlavors | Sequence[HTMLFlavors] | Nonerint | Sequence[int] | NonerarqrArprWrrbrrcrrGrrdrJrez dict | NonerfzIterable[object] | NonergrrXrrYrrhzDtypeBackend | lib.NoDefaultrCr'rzlist[DataFrame])Pr __future__r collectionsrr<rrtypingrrrrl pandas._libsr pandas.compat._optionalr pandas.errorsr r pandas.util._decoratorsr pandas.util._exceptionsrpandas.util._validatorsrpandas.core.dtypes.commonrpandasrpandas.core.indexes.baserpandas.core.indexes.multirpandas.core.seriesrpandas.core.shared_docsrpandas.io.commonrrrrrrrpandas.io.formats.printingrpandas.io.parsersrcollections.abcr r!pandas._typingr"r#r$r%r&r'r(r_RE_WHITESPACEr0rBrPrRrrr rr2r;r>rBrHrPr^ no_defaultrorr1r/rsl #  >(472*0%04( ! -.1?%&X: + Bf f R W(8Wt.=> R+'R+j12  1 ,  "F 8DN\"345 9=)-,037#'")- FJ25..&*'h"h h 7 h ' h * h1h !hhhhhh'hh !h"D#h$0%h&$'h()h6hr1