U Dx`=@s:dZddlmZddlZddlZddlZddlmZmZm Z m Z m Z m Z m Z ddlmZddlmZddlmZmZddlmZdd lmZdd lmZdd lmZdd lmZmZm Z m!Z!dd l"m#Z#ddl$m%Z%da&da'da(da)ddZ*e+dZ,e,fe-e-dddZ.ddZ/ddZ0GdddZ1Gddde1Z2e-ddd Z3d!d"iZ4d#Z5Gd$d%d%e1Z6d&d'Z7d(d)Z8e6e6e2e2d*Z9d+d,Z:e-dd-d.Z;d/d0Ze e>fe e e>e e>fe e e>e e>e?fe ee-e-fe@e e-e e-e-e ee@e@eed9d:d;ZAdS)=zW :mod:`pandas.io.html` is a module containing functionality for dealing with HTML IO. )abcN)DictListOptionalPatternSequenceTupleUnion)FilePathOrBuffer)import_optional_dependency)AbstractMethodErrorEmptyDataError)deprecate_nonkeyword_arguments) is_list_like)!create_series_with_explicit_dtype) DataFrame)is_urlstringify_pathurlopenvalidate_header_arg pprint_thing) TextParserFcCsRtrdStdddd}|dk atdddd}|dk atdddd}|dk adadS)Nbs4Fignore)Zraise_on_missingZ on_versionz lxml.etreehtml5libT)_IMPORTSr _HAS_BS4 _HAS_LXML _HAS_HTML5LIB)rlxmlrr!5/tmp/pip-target-zr53vnty/lib/python/pandas/io/html.py _importers!s"r#z[\r\n]+|\s{2,})sreturncCs|d|S)a Replace extra whitespace inside of a string with a single space. Parameters ---------- s : str or unicode The string from which to remove extra whitespace. regex : re.Pattern The regular expression to use to remove extra whitespace. Returns ------- subd : str or unicode `s` with all extra whitespace replaced with a single space.  )substrip)r$regexr!r!r"_remove_whitespace@sr*cCsnt|tr2|jpd|jpd}}tt||j|St|tjsFt |rJ|S|dkrVdSt t |j ddS)a Get an iterator given an integer, slice or container. Parameters ---------- skiprows : int, slice, container The iterator to use to skip rows; can also be a slice. Raises ------ TypeError * If `skiprows` is not a slice, integer, or Container Returns ------- it : iterable A proper iterator to use to skip rows of a DataFrame. rNz& is not a valid type for skipping rows) isinstanceslicestartsteplistrangestopnumbersIntegralr TypeErrortype__name__)skiprowsr.r/r!r!r" _get_skiprowsSs r9c Cst|r&t|}|}W5QRXnt|dr:|}n|t|ttfr|}z8tj |rt |d}|W5QRWSQRXWqt t fk rYqXnt dt |jd|S)z Try to read from a url, file or string. Parameters ---------- obj : str, unicode, or file-like Returns ------- raw_text : str readrbzCannot read object of type '')rrr:hasattrr,strbytesospathisfileopenr5 ValueErrorr6r7)objurltextfr!r!r"_readps       rIc@seZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZddZddZddZdS)_HtmlFrameParsera 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 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 Notes ----- To subclass this class effectively you must override the following methods: * :func:`_build_doc` * :func:`_attr_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. cCs"||_||_||_||_||_dSN)iomatchattrsencodingdisplayed_only)selfrLrMrNrOrPr!r!r"__init__s z_HtmlFrameParser.__init__cs(jj}fdd|DS)z Parse and return all tables from the DOM. Returns ------- list of parsed (header, body, footer) tuples from tables. c3s|]}|VqdSrK)_parse_thead_tbody_tfoot).0tablerQr!r" sz0_HtmlFrameParser.parse_tables..) _parse_tables _build_docrMrN)rQtablesr!rVr" parse_tablessz_HtmlFrameParser.parse_tablescCs ||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)rQrEattrr!r!r" _attr_gettersz_HtmlFrameParser._attr_gettercCs t|dS)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. Nr rQrEr!r!r" _text_gettersz_HtmlFrameParser._text_gettercCs t|dS)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. Nr_r`r!r!r" _parse_tdsz_HtmlFrameParser._parse_tdcCs t|dS)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. Nr_rQrUr!r!r"_parse_thead_tr s z _HtmlFrameParser._parse_thead_trcCs t|dS)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. Nr_rcr!r!r"_parse_tbody_trsz _HtmlFrameParser._parse_tbody_trcCs t|dS)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. Nr_rcr!r!r"_parse_tfoot_tr.s z _HtmlFrameParser._parse_tfoot_trcCs t|dS)ad Return all tables from the parsed DOM. Parameters ---------- doc : 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. Nr_)rQdocrMrNr!r!r"rX=sz_HtmlFrameParser._parse_tablescCs t|dS)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` Nr_rQrEtagr!r!r" _equals_tagWsz_HtmlFrameParser._equals_tagcCs t|dS)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. Nr_rVr!r!r"rYjs z_HtmlFrameParser._build_docc sx|}|}|}fdd}|sP|rP||drP||dq.|}|}|}|||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 Returns ------- list of list Each returned row is a list of str text. Notes ----- Any cell with ``rowspan`` or ``colspan`` will have its contents copied to subsequent cells. rr+rowspancolspan)rbrqrpr*raintr^r1)rQrowsZ all_texts remaindertrZtextsZnext_remainderindexZtdstdZprev_iZ prev_textZ prev_rowspanrGrvrw_r!r!r"rrsL            z(_HtmlFrameParser._expand_colspan_rowspancs|js |Sfdd|DS)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` cs.g|]&}dt|ddddkr|qS) display:nonestyler&)getattrr\replace)rTx attr_namer!r" s z:_HtmlFrameParser._handle_hidden_tables..)rP)rQZtbl_listrr!rr"_handle_hidden_tabless  z&_HtmlFrameParser._handle_hidden_tablesN)r7 __module__ __qualname____doc__rRr[r^rarbrdrerfrXrjrYrSrrrr!r!r!r"rJs7  -HrJcsheZdZdZfddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ZS)!_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`. cs(tj||ddlm}|d|_dS)Nr) SoupStrainerrU)superrRrr _strainer)rQargskwargsr __class__r!r"rRs z*_BeautifulSoupHtml5LibFrameParser.__init__c Cs|jj}|j||d}|s"tdg}t}||d}|D]V}|jrf|jtddD] } | qX||kr|j |ddk r| || |q<|stdt |j|S)N)rNzNo tables foundrNzdisplay:\s*none)rrGz!No tables found matching pattern )rnamefind_allrDsetrrPrecompileZ decomposefindrpaddreprpattern) rQrgrMrNZ element_namerZresultZ unique_tablesrUelemr!r!r"rXs"    z/_BeautifulSoupHtml5LibFrameParser._parse_tablescCs|jSrKrr`r!r!r"ra2sz._BeautifulSoupHtml5LibFrameParser._text_gettercCs |j|kSrK)rrhr!r!r"rj5sz-_BeautifulSoupHtml5LibFrameParser._equals_tagcCs|jdddS)N)r}rkF recursive)rrQrnr!r!r"rb8sz+_BeautifulSoupHtml5LibFrameParser._parse_tdcCs |dS)Nzthead trselectrcr!r!r"rd;sz1_BeautifulSoupHtml5LibFrameParser._parse_thead_trcCs |d}|jddd}||S)Nztbody trr{Fr)rrrQrUZ from_tbodyZ from_rootr!r!r"re>s z1_BeautifulSoupHtml5LibFrameParser._parse_tbody_trcCs |dS)Nztfoot trrrcr!r!r"rfDsz1_BeautifulSoupHtml5LibFrameParser._parse_tfoot_trcCs"t|j}|std|j|S)NzNo text parsed from document: )rIrLrD)rQZraw_textr!r!r"_setup_build_docGs z2_BeautifulSoupHtml5LibFrameParser._setup_build_doccCsRddlm}|}t|tr:|jdk r:||j}d}n |}|j}||d|dS)Nr) BeautifulSoupr)features from_encoding)rrrr,r?rOdecode)rQrZbdocZudocrr!r!r"rYMs  z,_BeautifulSoupHtml5LibFrameParser._build_doc)r7rrrrRrXrarjrbrdrerfrrY __classcell__r!r!rr"rs r)r%cCs:d|kr|d|d<ddd|D}d|dS)ar Build an xpath expression to simulate bs4's ability to pass in kwargs to search for attributes when using the lxml parser. Parameters ---------- attrs : dict A dict of HTML attributes. These are NOT checked for validity. Returns ------- expr : unicode An XPath expression that checks for the given HTML attributes. class_classz and cSs$g|]\}}d|dt|qS)@=)r)rTkvr!r!r"rmsz%_build_xpath_expr..[])rqjoinitems)rNr$r!r!r"_build_xpath_exprZsrrz$http://exslt.org/regular-expressions)httpfileftpcs`eZdZdZfddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ Z S)_LxmlFrameParseraY HTML to DataFrame parser that uses lxml under the hood. Warning ------- This parser can only handle HTTP, FTP, and FILE urls. See Also -------- _HtmlFrameParser _BeautifulSoupLxmlFrameParser Notes ----- Documentation strings for this class are in the base class :class:`_HtmlFrameParser`. cstj||dSrK)rrR)rQrrrr!r"rRsz_LxmlFrameParser.__init__cCs|SrK) text_contentr`r!r!r"rasz_LxmlFrameParser._text_gettercCs |dS)N ./td|./thxpathrr!r!r"rbsz_LxmlFrameParser._parse_tdc Cs|j}dt|d}|r&|t|7}|j|td}||d}|jr|D]<}|dD],}d|jdd d dkrX| |qXqJ|st d t||S) Nz//table//*[re:test(text(), z)]/ancestor::table) namespacesattribz .//*[@style]rrrr&zNo tables found matching regex ) rrrr _re_namespacerrPrr\rZ getparentremoverD) rQrgrMrrZ xpath_exprrZrUrr!r!r"rXs  z_LxmlFrameParser._parse_tablescCs |j|kSrK)rirhr!r!r"rjsz_LxmlFrameParser._equals_tagc Csddlm}ddlm}m}m}|d|jd}zbt|jr^t |j}|||d}W5QRXn||j|d}z | }Wnt k rYnXWnft t fk r}zDt|js||j|d}z | }Wqt k rYqXn|W5d}~XYnXt|ds|d ddd|S) 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)ZrecoverrO)parserNrzno text parsed from document)Z lxml.etreerZ lxml.htmlrrrrOrrLrgetrootAttributeErrorUnicodeDecodeErrorOSErrorr=) rQrrrrrrHrer!r!r"rYs.        z_LxmlFrameParser._build_doccCs@g}|dD],}||d|d}|r||q|S)Nz.//thead./trr)rextendrp)rQrUrytheadZelements_at_rootr!r!r"rds  z _LxmlFrameParser._parse_thead_trcCs|d}|d}||S)Nz .//tbody//trrrrr!r!r"res  z _LxmlFrameParser._parse_tbody_trcCs |dS)Nz .//tfoot//trrrcr!r!r"rfsz _LxmlFrameParser._parse_tfoot_tr)r7rrrrRrarbrXrjrYrdrerfrr!r!rr"rus 0rcCsbdd|D}t|td}|}|||k}dg}|D] \}}|||||7<q.)Zdtype_if_emptyr)robjectmaxr)rtdataZlensZlens_maxZnot_maxemptyindlengthr!r!r"_expand_elementss  rc Ks|d\}}}|d}t|d|d<|rb||}|dkrbt|dkrPd}nddt|D}|rn||7}t|t|fd|i|}|W5QRSQRXdS)Nrrsr8r+rcSs&g|]\}}tdd|Dr|qS)css|] }|VqdSrKr!)rTrGr!r!r"rWsz,_data_to_frame...)any)rTirnr!r!r"rsz"_data_to_frame..)rqr9r enumeraterrr:)rheadrtZfootrstpr!r!r"_data_to_frame s  r)r NrrcCshtt}||kr*tt|d||dkrTts>tdtsJtdtd}n t s`tdt|S)a Choose the parser based on the input flavor. Parameters ---------- flavor : str 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 )rrz%html5lib not found, please install itz1BeautifulSoup4 (bs4) not found, please install itrz!lxml not found, please install it) r0_valid_parserskeysrDrr ImportErrorrr r)flavorZ valid_parsersrr!r!r"_parser_dispatch)s  rcCs ddd|D}d|dS)Nz, css|]}t|VqdSrKr)rTelr!r!r"rWSsz _print_as_set..{})r)r$argr!r!r" _print_as_setRsrcCs|dkrd}nvt|tr |f}ndt|tjrZtdd|Dstdtt|jdn*t|trlt|nt|}|d7}t |t |}t t }t |}||@st t |dt ||S)N)r rcss|]}t|tVqdSrK)r,r>)rTflavr!r!r"rW]sz#_validate_flavor..zObject of type z is not an iterable of stringsz is not a valid flavorz2 is not a valid set of flavors, valid flavors are )r,r>rIterablermr5rr6r7rDtuplerrr)rmsgZ valid_flavorsZ flavor_setr!r!r"_validate_flavorWs(  rc Ks t|}t|}d}|D]} t| } | |||||} z | } Wnhtk r} zJt|drr|rr|dn$t|dr|std| d| | }W5d} ~ XYqXqq|dk st |g}| D]<}z| t fd|i|Wqt k rYqYqXq|S)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) rrrrr[rDr=rseekAssertionErrorrprr )rrLrMrNrOrPrZcompiled_matchZretainedrrprZZcaughtretrUr!r!r"_parsess8      rz2.0)version.+,.T)rLrMrrs index_colr8rN parse_dates thousandsrOdecimal converterskeep_default_narPr%cCsXtt|tjr"|dkr"tdt|t|}t|||||||||| | | | | |dS)a Read HTML tables into a ``list`` of ``DataFrame`` objects. Parameters ---------- io : str, path object or file-like object A URL, a file-like object, or a raw string containing HTML. 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'``. 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 : str, optional The parsing engine 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. 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 cstfdd|DS)Nc3s|]}|dVqdS)thN)rj)rTtrVr!r"rWszS_HtmlFrameParser._parse_thead_tbody_tfoot..row_is_all_th..)allrb)rowrVr!r" row_is_all_thsz@_HtmlFrameParser._parse_thead_tbody_tfoot..row_is_all_thr)rdrerfappendpop_expand_colspan_rowspan) rQZ table_htmlZ header_rowsZ body_rowsZ footer_rowsroheaderbodyfooterr!rVr"rSus       z)_HtmlFrameParser._parse_thead_tbody_tfootc Csg}g}|D].}g}g}d}||}|D]} |r|dd|kr|d\} } } || | dkrz|| | | df|d7}q0t|| } t|| dpd}t|| dpd}t|D]2}|| |dkr||| |df|d7}qq,|D]0\} } } || | dkr|| | | dfq|||}q |rg}g}|D]4\} } } || | dkrP|| | | dfqP|||}q>|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))rrLrMrsrr8rrrNrOrr na_valuesrrP)r#r,r3r4rDrrr)rLrMrrsrr8rNrrrOrrrrrPr!r!r" read_htmls2r)rNNNNNFrNrNNTT)Br collectionsrr3r@rtypingrrrrrrr Zpandas._typingr Zpandas.compat._optionalr Z pandas.errorsr r Zpandas.util._decoratorsrZpandas.core.dtypes.commonrZpandas.core.constructionrZpandas.core.framerZpandas.io.commonrrrrZpandas.io.formats.printingrZpandas.io.parsersrrrrrr#rZ_RE_WHITESPACEr>r*r9rIrJrrrZ_valid_schemesrrrrrrrrrxr-boolrr!r!r!r"s $         yU  ))