B []@s`dZddlmZddlZddlZddlZddlmZddlm Z ddl m Z m Z ddl mZddlmZdd lmZmZmZdd lmZdd lmZd ad ad ad ad dZedZefddZ ddZ!ddZ"GdddZ#Gddde#Z$ddZ%ddiZ&dZ'Gdd d e#Z(d!d"Z)d#d$Z*e(e(e$e$d%Z+d&d'Z,d(d)Z-d*d+Z.d,d-Z/d4d2d3Z0dS)5zV:mod:`pandas.io.html` is a module containing functionality for dealing with HTML IO. )abcN)raise_with_traceback)import_optional_dependency)AbstractMethodErrorEmptyDataError) is_list_like)Series)_is_url_validate_header_argurlopen) pprint_thing) TextParserFcCsRtrdStdddd}|dk atdddd}|dk atdddd}|dk adadS)Nbs4Fignore)Zraise_on_missingZ on_versionz lxml.etreehtml5libT)_IMPORTSr_HAS_BS4 _HAS_LXML _HAS_HTML5LIB)rlxmlrr2/tmp/pip-install-svzetoqp/pandas/pandas/io/html.py _importerss  rz[\r\n]+|\s{2,}cCs|d|S)aReplace extra whitespace inside of a string with a single space. Parameters ---------- s : str or unicode The string from which to remove extra whitespace. regex : regex 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)sregexrrr_remove_whitespace<srcCslt|tr2|jpd|jpd}}tt||j|St|tjsFt |rJ|S|dkrVdSt dt |j dS)aGet 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(%r is not a valid type for skipping rows) isinstanceslicestartsteplistrangestopnumbersIntegralr TypeErrortype__name__)skiprowsr"r#rrr _get_skiprowsOs r-c Cst|r&t|}|}WdQRXn~t|dr:|}njt|ttfr|}y*tj |rtt |d }|SQRXWqt t fk rYqXnt dt |j|S)zTry to read from a url, file or string. Parameters ---------- obj : str, unicode, or file-like Returns ------- raw_text : str NreadrbzCannot read object of type %r)r r r.hasattrr strbytesospathisfileopenr) ValueErrorr*r+)objurltextfrrr_readms      r<c@seZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZddZddZddZdS)_HtmlFrameParseraBase 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 .. versionadded:: 0.23.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 .. versionadded:: 0.23.0 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"||_||_||_||_||_dS)N)iomatchattrsencodingdisplayed_only)selfr>r?r@rArBrrr__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|]}|VqdS)N)_parse_thead_tbody_tfoot).0table)rCrr sz0_HtmlFrameParser.parse_tables..) _parse_tables _build_docr?r@)rCtablesr)rCr 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)rCr8attrrrr _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. N)r)rCr8rrr _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. N)r)rCr8rrr _parse_tds z_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. N)r)rCrGrrr_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. N)r)rCrGrrr_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. N)r)rCrGrrr_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. N)r)rCdocr?r@rrrrI;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` N)r)rCr8tagrrr _equals_tagUsz_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. N)r)rCrrrrJhs z_HtmlFrameParser._build_docc s||}|}|}fdd}|sTx$|rR||drR||dq0W|}|}|}|||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. rrrowspancolspan)rQr^r]rrPintrOr%)rCrowsZ all_texts remaindertrZtextsZnext_remainderindexZtdstdZprev_iZ prev_textZ prev_rowspanr:rcrd_rrrr_sL            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)z display:nonestyler)getattrrMreplace)rFx) attr_namerr sz:_HtmlFrameParser._handle_hidden_tables..)rB)rCZtbl_listrqr)rqr_handle_hidden_tabless z&_HtmlFrameParser._handle_hidden_tablesN)r+ __module__ __qualname____doc__rDrLrOrPrQrRrSrTrIrWrJrEr_rsrrrrr=s9  .Ir=csheZdZdZfddZddZddZdd 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) SoupStrainerrG)superrDrrx _strainer)rCargskwargsrx) __class__rrrDs z*_BeautifulSoupHtml5LibFrameParser.__init__c Cs|jj}|j||d}|s"tdg}t}||d}xb|D]Z}|jrlx"|jtddD] } | q\W||kr|j |ddk r| || |q>W|stdj |jd|S) N)r@zNo tables foundr@zdisplay:\s*none)rl)r:z)No tables found matching pattern {patt!r})patt)rznamefind_allr7setrsrBrecompileZ decomposefindr]addformatpattern) rCrUr?r@Z element_namerKresultZ unique_tablesrGelemrrrrIs$    z/_BeautifulSoupHtml5LibFrameParser._parse_tablescCs|jS)N)r:)rCr8rrrrP3sz._BeautifulSoupHtml5LibFrameParser._text_gettercCs |j|kS)N)r)rCr8rVrrrrW6sz-_BeautifulSoupHtml5LibFrameParser._equals_tagcCs|jdddS)N)rjrXF) recursive)r)rCr[rrrrQ9sz+_BeautifulSoupHtml5LibFrameParser._parse_tdcCs |dS)Nzthead tr)select)rCrGrrrrR<sz1_BeautifulSoupHtml5LibFrameParser._parse_thead_trcCs |d}|jddd}||S)Nztbody trrhF)r)rr)rCrG from_tbody from_rootrrrrS?s z1_BeautifulSoupHtml5LibFrameParser._parse_tbody_trcCs |dS)Nztfoot tr)r)rCrGrrrrTEsz1_BeautifulSoupHtml5LibFrameParser._parse_tfoot_trcCs$t|j}|s tdj|jd|S)Nz#No text parsed from document: {doc})rU)r<r>r7r)rCZraw_textrrr_setup_build_docHs z2_BeautifulSoupHtml5LibFrameParser._setup_build_doccCs ddlm}||d|jdS)Nr) BeautifulSoupr)featuresZ from_encoding)rrrrA)rCrrrrrJNs z,_BeautifulSoupHtml5LibFrameParser._build_doc)r+rtrurvrDrIrPrWrQrRrSrTrrJ __classcell__rr)r}rrws  rwcCs:d|kr|d|d<dd|D}djd|dS)amBuild 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_classcSsg|]\}}dj||dqS)z@{key}={val!r})keyval)r)rFkvrrrrrhsz%_build_xpath_expr..z[{expr}]z and )expr)r^itemsrjoin)r@rrrr_build_xpath_exprVsrrz$http://exslt.org/regular-expressions)httpfileftpcs`eZdZdZfddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ Z S)_LxmlFrameParseraTHTML 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||dS)N)ryrD)rCr{r|)r}rrrDsz_LxmlFrameParser.__init__cCs|S)N) text_content)rCr8rrrrPsz_LxmlFrameParser._text_gettercCs |dS)Nz ./td|./th)xpath)rCr[rrrrQsz_LxmlFrameParser._parse_tdc Cs|j}d}|j|d}|r&|t|7}|j|td}||d}|jrxH|D]@}x:|dD],} d| jdd d dkr\| | q\WqLW|st d j|d|S) Nz5//table//*[re:test(text(), {patt!r})]/ancestor::table)r~) namespacesattribz .//*[@style]z display:nonerlrmrz'No tables found matching regex {patt!r}) rrrr _re_namespacersrBrrMroZ getparentremover7) rCrUr?r|rqueryZ xpath_exprrKrGrrrrrIs     z_LxmlFrameParser._parse_tablescCs |j|kS)N)rV)rCr8rVrrrrWsz_LxmlFrameParser._equals_tagc Csddlm}m}m}ddlm}|d|jd}ybt|jr^t |j}|||d}WdQRXn||j|d}y | }Wnt k rYnXWnft t fk r}zDt|js||j|d}y | }Wqt k rYqXn|Wdd}~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)parse fromstring HTMLParser)XMLSyntaxErrorT)ZrecoverrA)parserNrzno text parsed from document)Z lxml.htmlrrrZ lxml.etreerrAr r>r getrootAttributeErrorUnicodeDecodeErrorIOErrorr0) rCrrrrrr;rerrrrJs.        z_LxmlFrameParser._build_doccCsDg}x:|dD],}||d|d}|r||qW|S)Nz.//theadz./trz ./td|./th)rextendr])rCrGrftheadZelements_at_rootrrrrRs z _LxmlFrameParser._parse_thead_trcCs|d}|d}||S)Nz .//tbody//trz./tr)r)rCrGrrrrrrSs  z _LxmlFrameParser._parse_tbody_trcCs |dS)Nz .//tfoot//tr)r)rCrGrrrrTsz _LxmlFrameParser._parse_tfoot_tr)r+rtrurvrDrPrQrIrWrJrRrSrTrrr)r}rrps 0rcCs^tdd|D}|}|||k}dg}x,|D] \}}|||||7<q6WdS)NcSsg|] }t|qSr)len)rFrrrrrrsz$_expand_elements..rm)rmaxr)raZlensZlens_maxZnot_maxemptyindlengthrrr_expand_elementss  rcKs|d\}}}|d}t|d|d<|rb||}|dkrbt|dkrPd}nddt|D}|rn||7}t|t|fd|i|}|}|S)Ndatar`r,rrcSs&g|]\}}tdd|Dr|qS)css|] }|VqdS)Nr)rFr:rrrrHsz,_data_to_frame...)any)rFir[rrrrrsz"_data_to_frame..)r^r-r enumeraterr r.)r|headraZfootr`tpZdfrrr_data_to_frames  r)rNrrcCsdtt}||kr&tdj||d|dkrPts:tdtsFtdtd}n t s\tdt|S)aChoose 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<{invalid!r} is not a valid flavor, valid flavors are {valid})invalidvalid)rrz%html5lib not found, please install itz1BeautifulSoup4 (bs4) not found, please install itrz!lxml not found, please install it) r$_valid_parserskeysr7rr ImportErrorrrr)flavorZ valid_parsersrrrr_parser_dispatch&s   rcCs$ddjddd|DddS)N{z{arg}z, css|]}t|VqdS)N)r )rFelrrrrHPsz _print_as_set..)arg})rr)rrrr _print_as_setOsrcCs|dkrd}nrt|tr |f}n`t|tjrVtdd|Dstdjt|jdn*t|trddnd}|d7}t |j|d t |}t t }t |}||@st d jt |t |d |S) N)rrcss|]}t|tVqdS)N)r r1)rFflavrrrrHYsz#_validate_flavor..z4Object of type {typ!r} is not an iterable of strings)typz {flavor!r}z{flavor}z is not a valid flavor)rzB{invalid} is not a valid set of flavors, valid flavors are {valid})rr)r r1rIterablerZr)rr*r+r7tuplerrr)rfmtZ valid_flavorsZ flavor_setrrr_validate_flavorSs(  rc Kst|}t|}d}x|D]} t| } | |||||} y | } Wndtk r} zFt|drt|rt|dn t|dr|st d | | }Wdd} ~ XYqXPqWt |g}x@| D]8}y| t fd|i|Wqtk rwYqXqW|S)NseekablerzThe flavor {} 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)rrrrrL Exceptionr0rseekr7rrr]rr)rr>r?r@rArBr|Zcompiled_matchZretainedrrprKZcaughtretrGrrr_parseqs2      r.+,.TcCsPtt|tjr"|dkr"tdt|t|||||||||| | | | | |dS)a3Read 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 or None, container of strings 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 or None, 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 or None, optional The column (or list of columns) to use to create the index. skiprows : int or list-like or slice or None, optional 0-based. Number of rows to skip after parsing the column integer. 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 or None, 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 or None, 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). .. versionadded:: 0.19.0 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. .. versionadded:: 0.19.0 na_values : iterable, default None Custom NA values .. versionadded:: 0.19.0 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 .. versionadded:: 0.19.0 displayed_only : bool, default True Whether elements with "display: none" should be parsed .. versionadded:: 0.23.0 Returns ------- dfs : list of DataFrames See Also -------- read_csv 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)rW)rFt)rCrrrHszS_HtmlFrameParser._parse_thead_tbody_tfoot..row_is_all_th..)allrQ)row)rCrr row_is_all_thsz@_HtmlFrameParser._parse_thead_tbody_tfoot..row_is_all_thr)rRrSrTappendpop_expand_colspan_rowspan) rCZ table_htmlZ header_rowsZ body_rowsZ footer_rowsr\headerbodyfooterr)rCrrEss       z)_HtmlFrameParser._parse_thead_tbody_tfootc Csg}g}xL|D]B}g}g}d}||}x|D]} xV|r|dd|kr|d\} } } || | dkr|| | | df|d7}q8Wt|| } t|| dpd}t|| dpd}x>t|D]2}|| |dkr||| |df|d7}qWq2Wx<|D]4\} } } || | dkr|| | | dfqW|||}qWx`|rg}g}x<|D]4\} } } || | dkrn|| | | dfqnW|||}qZW|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). .. versionadded:: 0.21.0 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))rr>r?r` index_colr, parse_dates thousandsr@rAdecimal converters na_valueskeep_default_narB)rr r'r(r7r r)r>r?rr`rr,r@rrrArrrrrBrrr read_htmls,r)rNNNNNFrNrNNTT)1rv collectionsrr'r3rZ pandas.compatrZpandas.compat._optionalrZ pandas.errorsrrZpandas.core.dtypes.commonrZpandasrZpandas.io.commonr r r Zpandas.io.formats.printingr Zpandas.io.parsersr rrrrrrZ_RE_WHITESPACErr-r<r=rwrrZ_valid_schemesrrrrrrrrrrrrrsl         }Q  ),