Ë
    |`,�  ã                   óT  — d Z ddlmZmZmZmZ ddlZddlZddlZddl	Z	ddl
mZ ddlmZ ddlmZ ddlmZ ddlmZ e	j(                  d	k  ZereecZZerdd
lmZ ddlmZ ddlmZ ddlmZ ddl m!Z! ndd
l"mZ ddl#mZ ddl$mZ ddl%m!Z! erddl&m'Z' e'd„ «       Z(nddl&m(Z( ddl)m*Z*  e*jV                  d«      Z,ddgZ-d>d„Z. G d„ de«      Z/d?d„Z0 ed«      duZ1e1r@e,je                  d«       ddl3m4Z5 ddl6m7Z7 e5jp                  Z8e5jr                  jt                  Z:nddl;m5Z5 ddl<m7Z7  G d„ d «      Z8d!„ Z:i Z= G d"„ d#«      Z> G d$„ d%e>«      Z? G d&„ d'e>«      Z@ G d(„ d)«      ZAd*„ ZBd+„ ZCd,„ ZDd@d-„ZE G d.„ d/«      ZFeBeCeDd0œZG eFeG«      ZH	  ed«       eej’                  d1«      d2„ d3„ d4œZJ eFeJ«      ZK	 eLeMeNeOej                   ej¢                  ej¤                  ej¦                  ej¨                  ejª                  d5œ
ZV eFeV«      ZW	 d6„ ZXdAd7„ZYd8„ ZZd9„ Z[dBd:„Z\d;„ Z]dAd<„Z^e_d=k(  r e^«        yy)Ca‹  Piculet is a module for scraping XML and HTML documents using XPath queries.

It consists of this single source file with no dependencies other than
the standard library, which makes it very easy to integrate into applications.
It has been tested with Python 2.7, Python 3.4+, PyPy2 5.7+, and PyPy3 5.7+.

For more information, please refer to the documentation:
https://piculet.readthedocs.io/
é    )Úabsolute_importÚdivisionÚprint_functionÚunicode_literalsN)ÚArgumentParser)Údeque)Úpartial)Ú
itemgetter)Úfind_loader)é   r   )Úescape)Ú
HTMLParser)ÚStringIO)Úname2codepoint)Úurlopen)Úcontextmanagerc              #   ó„   K  — t         j                  | c}t         _        	 | –— |t         _        y# |t         _        w xY w­w)z3Context manager for temporarily redirecting stdout.N)ÚsysÚstdout)Ú
new_stdoutÚ
old_stdouts     ú:/usr/lib/python3/dist-packages/imdb/parser/http/piculet.pyÚredirect_stdoutr   >   s3   è ø€ ô "%§¡¨ZÐˆ
”C”Jð	$ØÒà#ŒC�Jø˜ŒC�Jüs   ‚A  0 ¤A °=½A )r   )ÚloggerÚpiculets<   <meta http-equiv="content-type" content="text/html; charset=s   <meta charset="c                 ó^  — |€…t         D ]d  }| j                  |«      }|dk\  sŒ|t        |«      z   }| j                  d|«      }| || j                  d«      }t        j                  d|«        n t        j                  d|«       |}t        j                  d|«       | j                  |«      S )aÁ  Decode an HTML document according to a character set.

    If no character set is given, this will try to figure it out
    from the corresponding ``meta`` tags.

    :sig: (bytes, Optional[str], Optional[str]) -> str
    :param content: Content of HTML document to decode.
    :param charset: Character set of the page.
    :param fallback_charset: Character set to use if it can't be figured out.
    :return: Decoded content of the document.
    r   ó   "Úasciizcharset found in "meta": "%s"z'charset not found, using fallback: "%s"zdecoding for charset: "%s")Ú_CHARSET_TAGSÚfindÚlenÚdecodeÚ_loggerÚdebug)ÚcontentÚcharsetÚfallback_charsetÚtagÚstartÚcharset_startÚcharset_ends          r   Údecode_htmlr,   Z   s©   € ð €Ü ò 
	'ˆCØ—L‘L Ó%ˆEØ˜‹zØ %¬¨C«Ñ 0�Ø%Ÿl™l¨4°Ó?�Ø! -°Ð<×CÑCÀGÓL�Ü—‘Ð=¸wÔGÙð
	'ô �M‰MÐCÐEUÔVØ&ˆGÜ‡M�MÐ.°Ô8Ø�>‰>˜'Ó"Ð"ó    c                   óL   ‡ — e Zd ZdZh d£Z	 d	ˆ fd„	Zd„ Zd„ Zd„ Zd„ Z	d„ Z
ˆ xZS )
ÚHTMLNormalizerzZHTML cleaner and XHTML convertor.

    DOCTYPE declarations and comments are removed.
    >   ÚbrÚhrÚimgÚlinkÚmetaÚinputc                 ó
  •— t         rt        j                  | «       nt        ‰| �	  d¬«       |�t	        |«      n	t	        «       | _        |�t	        |«      n	t	        «       | _        t        «       | _        t        «       | _	        y)zçInitialize this normalizer.

        :sig: (Optional[Iterable[str]], Optional[Iterable[str]]) -> None
        :param omit_tags: Tags to remove, along with all their content.
        :param omit_attrs: Attributes to remove.
        T)Úconvert_charrefsN)
ÚPY2r   Ú__init__ÚsuperÚsetÚ	omit_tagsÚ
omit_attrsr   Ú
_open_tagsÚ_open_omitted_tags)Úselfr<   r=   Ú	__class__s      €r   r9   zHTMLNormalizer.__init__   sc   ø€ õ Ü×Ñ Õ%ä‰GÑ¨dÐÔ3à+4Ð+@œ˜YœÄcÃeˆŒØ-7Ð-Cœ#˜jœ/ÌËˆŒô  ›'ˆŒÜ"'£'ˆÕr-   c                 ó  — || j                   v r1t        j                  d|«       | j                  j	                  |«       | j                  �s6d|v rt        d|z  d¬«       y|dk(  r8| j                  d   dk(  r&t        j                  d	«       | j                  d«       g }|D ]j  \  }}|| j                  v rt        j                  d
||«       Œ,|€t        j                  d||«       d}d|t        |d¬«      dœz  }|j	                  |«       Œl d|t        |«      dkD  rddj                  |«      z   nd|| j                  v rdnddœz  }t        |d¬«       || j                  vr| j                  j	                  |«       yyy)z&Process the starting of a new element.zomitting: "%s"ú@z
&lt;%s&gt;Ú ©ÚendNÚliéÿÿÿÿz=opened "li" without closing previous "li", adding closing tagzomitting "%s" attribute of "%s"z7no value for "%s" attribute of "%s", adding empty valuez%(name)s="%(value)s"T)Úquote©ÚnameÚvaluez<%(tag)s%(attrs)s%(slash)s>r   ú z /)r(   ÚattrsÚslash)r<   r#   r$   r?   ÚappendÚprintr>   Úhandle_endtagr=   Úhtml_escaper!   ÚjoinÚSELF_CLOSING_TAGS)r@   r(   rN   Ú
attributesÚ	attr_nameÚ
attr_valueÚmarkupÚlines           r   Úhandle_starttagzHTMLNormalizer.handle_starttag’   s…  € à�$—.‘.Ñ Ü�M‰MÐ*¨CÔ0Ø×#Ñ#×*Ñ*¨3Ô/Ø×&Ó&à�c‰zä�l SÑ(¨bÕ1ØØ�t’ $§/¡/°"Ñ"5¸Ò"=Ü—‘Ð]Ô^Ø×"Ñ" 4Ô(ØˆJØ).ò *Ñ%�	˜:Ø §¡Ñ/Ü—M‘MÐ"CÀYÐPSÔTØØÐ%Ü—M‘MÐ"[Ø"+¨Sô2à!#�JØ/Ø%Ü(¨¸4Ô@ñ3ñ �ð ×!Ñ! &Õ)ð*ð 1ØÜ9<¸Z»È1Ò9L˜# §¡¨Ó 4Ò4ÐRTØ!$¨×(>Ñ(>Ñ!>™ÀBñ4ñ ˆDô
 �$˜BÕØ˜$×0Ñ0Ñ0Ø—‘×&Ñ& sÕ+ð 1ð; 'r-   c                 óè  — | j                   �s)|| j                  v�r| j                  d   }|dk(  r+|dk(  r&t        j	                  d«       | j                  d«       ||k(  r-t        dd|iz  d¬«       | j                  j                  «        y|| j                  vrt        j	                  d	|«       y|| j                  d
   k(  rpt        j	                  d||«       t        dd|iz  d¬«       t        dd|iz  d¬«       | j                  j                  «        | j                  j                  «        yyy|| j                  v r.|| j                   d   k(  r| j                   j                  «        yyy)z!Process the ending of an element.rH   ÚulrG   z:closing "ul" without closing last "li", adding closing tagz
</%(tag)s>r(   rD   rE   z$closing tag "%s" without opening tagéþÿÿÿz9unexpected closing tag "%s" instead of "%s", closing bothN)	r?   rU   r>   r#   r$   rR   rQ   Úpopr<   )r@   r(   Úlasts      r   rR   zHTMLNormalizer.handle_endtag·   sD  € à×&Ó&à˜$×0Ñ0Ò0Ø—‘ rÑ*�Ø˜4’K d¨d¢lÜ—M‘MÐ"^Ô_Ø×&Ñ& tÔ,Ø˜$’;ä˜,¨%°¨Ñ5¸2Õ>Ø—O‘O×'Ñ'Õ)Ø §¡Ñ/Ü—M‘MÐ"HÈ#ÕNà˜DŸO™O¨BÑ/Ò/Ü—M‘MÐ"]Ø"% tô-ä˜,¨%°¨Ñ6¸BÕ?Ü˜,¨%°¨Ñ5¸2Õ>Ø—O‘O×'Ñ'Ô)Ø—O‘O×'Ñ'Õ)ð 0ð 1ð& �T—^‘^Ñ#¨#°×1HÑ1HÈÑ1LÒ*Là×#Ñ#×'Ñ'Õ)ð +MÐ#r-   c                 óœ   — | j                   s@t        |«      }t        t        r!t	        |t
        «      r|j                  d«      n|d¬«       yy)z!Process collected character data.úutf-8rD   rE   N)r?   rS   rQ   r8   Ú
isinstanceÚbytesr"   )r@   ÚdatarZ   s      r   Úhandle_datazHTMLNormalizer.handle_dataÒ   s;   € à×&Ò&ä˜tÓ$ˆDÜ­#´*¸TÄ5Ô2I�$—+‘+˜gÔ&ÈtÐY[Ö\ð 'r-   c                 óX   — t        j                  |«      }|�t        dd|iz  d¬«       yy)zProcess an entity reference.Nz
&#%(ref)d;ÚrefrD   rE   )r   ÚgetrQ   )r@   rK   Únums      r   Úhandle_entityrefzHTMLNormalizer.handle_entityrefÙ   s1   € ô × Ñ  Ó&ˆØˆ?Ü�, %¨ Ñ-°2Ö6ð r-   c                 ó(   — t        dd|iz  d¬«       y)zProcess a character reference.z
&#%(ref)s;rh   rD   rE   N)rQ   )r@   rK   s     r   Úhandle_charrefzHTMLNormalizer.handle_charrefà   s   € ô 	ˆl˜e T˜]Ñ*°Ö3r-   ©NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rU   r9   r[   rR   rf   rk   rm   Ú__classcell__©rA   s   @r   r/   r/   v   s4   ø„ ñò
 EÐØ)õ*ò&#,òJ*ò6]ò7ö4r-   r/   c                 óÐ   — t        «       }t        ||¬«      }t        |«      5  |j                  | «       ddd«       |j	                  «       S # 1 sw Y   |j	                  «       S xY w)aD  Clean HTML and convert to XHTML.

    :sig: (str, Optional[Iterable[str]], Optional[Iterable[str]]) -> str
    :param document: HTML document to clean and convert.
    :param omit_tags: Tags to exclude from the output.
    :param omit_attrs: Attributes to exclude from the output.
    :return: Normalized XHTML content.
    )r<   r=   N)r   r/   r   ÚfeedÚgetvalue)Údocumentr<   r=   ÚoutÚ
normalizers        r   Úhtml_to_xhtmlr{   ì   sS   € ô ‹*€CÜ¨)À
ÔK€JÜ	˜Ó	ñ "Ø�‰˜Ô!÷"à�<‰<‹>Ð÷"à�<‰<‹>Ðús   £AÁA%Úlxmlz
using lxml)Úetree)ÚElement)ÚElementTreec                   ó   — e Zd ZdZd„ Zd„ Zy)ÚXPathz¶An XPath expression evaluator.

        This class is mainly needed to compensate for the lack of ``text()``
        and ``@attr`` axis queries in ElementTree XPath support.
        c                 ó’  ‡— ˆfd„}ˆfd„}d„ }‰d   dk(  rd‰z   Š‰j                  d«      r
|}|| _        y	‰j                  d«      r
|}|| _        y	‰j                  d«      }|d	d
 |d
   }}|j                  d«      r(t        |dj	                  |«      |dd	 ¬«      }|| _        y	t        t
        j                  ‰¬«      }|| _        y	)zInitialize this evaluator.

            :sig: (str) -> None
            :param path: XPath expression to evaluate.
            c                 óˆ   •— | j                  ‰d d «      D ��cg c]  }|j                  «       D ]  }|sŒ|‘Œ	 Œ c}}S c c}}w )Niøÿÿÿ)ÚfindallÚitertext)ÚelementÚeÚtÚpaths      €r   Ú
descendantz"XPath.__init__.<locals>.descendant  s;   ø€ à#*§?¡?°4¸¸°9Ó#=×Y˜aÀqÇzÁzÃ|ÒYÀ!ÒWXšÐY˜ÓYÐYùÓYs   ™>´>c           
      óâ   •— | j                  ‰d d «      D ���cg c]A  }|j                  g|D �cg c]  }|j                  r|j                  nd‘Œ c}z   D ]  }|r|‘Œ ŒC c}}}S c c}w c c}}}w )NiùÿÿÿrD   )r„   ÚtextÚtail)r†   r‡   rˆ   Úcr‰   s       €r   ÚchildzXPath.__init__.<locals>.child!  s{   ø€ à#*§?¡?°4¸¸°9Ó#=÷ Zð Z˜aØ#$§6¡6 (ÐPQÖ-RÈ1¸¿º¨a¯fªfÀBÑ.FÒ-RÑ"RòZØÑWXò ð Z˜ô Zð ZùÚ-RùôZs   šA*¯!A%ÁA*Á%A*c                 óª   — | j                  |«      D �cg c]  }|j                  j                  |«      ‘Œ }}|D �cg c]  }|€Œ|‘Œ	 c}S c c}w c c}w ©N)r„   Úattribri   )r†   ÚsubpathÚattrr‡   ÚresultÚrs         r   Ú	attributez!XPath.__init__.<locals>.attribute&  sI   € Ø6=·o±oÀgÓ6NÖO°˜!Ÿ(™(Ÿ,™, tÕ,ÐO�ÐOØ#)Ö;˜a¨Q©]šÒ;Ð;ùò PùÚ;s   ”"A¼AÁAr   ú/ú.z//text()z/text()NrH   rC   é   )r“   r”   )r‰   )ÚendswithÚsplitÚ
startswithr	   rT   r~   r„   Ú_apply)	r@   r‰   rŠ   r�   r—   rž   ÚstepsÚfrontr`   s	    `       r   r9   zXPath.__init__  sÐ   ø€ ôZôZò
<ð �A‰w˜#Š~ð ˜T‘z�à�}‰}˜ZÔ(Ø#�ð !ˆD�Kð —‘˜yÔ)Ø�ð !ˆD�Kð Ÿ
™
 3›�Ø# C R˜j¨%°©)�t�à—?‘? 3Ô'Ü$ Y¸¿¹À»ÈdÐSTÐSUÈhÔW�Fð !ˆD�Kô %¤W§_¡_¸4Ô@�Fà ˆD�Kr-   c                 ó$   — | j                  |«      S )zàApply this evaluator to an element.

            :sig: (Element) -> XPathResult
            :param element: Element to apply this expression to.
            :return: Elements or strings resulting from the query.
            )rž   ©r@   r†   s     r   Ú__call__zXPath.__call__>  s   € ð —;‘;˜wÓ'Ð'r-   N)ro   rp   rq   rr   r9   r£   © r-   r   r�   r�     s   „ ñ	ò%	!óN	(r-   r�   c                 ó$   —  t        |«      | «      S r‘   )r�   )r‡   Úps     r   ú<lambda>r§   G  s   € ˜œ˜q› !›€ r-   c                   ó6   — e Zd ZdZdd„Zd„ Zdd„Zed„ «       Zy)	Ú	Extractorz?Abstract base extractor for getting data out of an XML element.Nc                 óH   — || _         	 |�t        |«      | _        yd| _        y)zóInitialize this extractor.

        :sig: (Optional[Transformer], Optional[str]) -> None
        :param transform: Function to transform the extracted value.
        :param foreach: Path to apply for generating a collection of values.
        N)Ú	transformr�   Úforeach)r@   r«   r¬   s      r   r9   zExtractor.__init__W  s/   € ð #ˆŒØ8à)0Ð)<”u˜W“~ˆŒØBð CGˆŒØBr-   c                 ó   — t        d«      ‚)zÊGet the raw data from an element using this extractor.

        :sig: (Element) -> ExtractedItem
        :param element: Element to apply this extractor to.
        :return: Extracted raw data.
        z.Concrete extractors must implement this method)ÚNotImplementedErrorr¢   s     r   ÚapplyzExtractor.applyd  s   € ô "Ð"RÓSÐSr-   c                 ó~   — | j                  |«      }|�
|t        u s|s|S | j                  €|S | j                  |«      S )a8  Get the processed data from an element using this extractor.

        :sig: (Element, Optional[bool]) -> Any
        :param element: Element to extract the data from.
        :param transform: Whether the transformation will be applied or not.
        :return: Extracted and optionally transformed data.
        )r¯   Ú_EMPTYr«   )r@   r†   r«   rL   s       r   ÚextractzExtractor.extractm  sA   € ð —
‘
˜7Ó#ˆØˆM˜u¬™¹	ØˆLØŸ™Ð.ˆuÐI°D·N±NÀ5Ó4IÐIr-   c                 óü  — | j                  d«      }|€d}n"t        j                  |«      }|€t        d«      ‚| j                  d«      }| j                  d«      }|�I| j                  d«      }|€d}n"t        j                  |«      }|€t        d«      ‚t	        ||||¬«      }|S | j                  d	«      }|D �	cg c]  }	t
        j                  |	«      ‘Œ }
}	t        |
| j                  d
«      ||¬«      }|S c c}	w )zÿGenerate an extractor from a description map.

        :sig: (Mapping[str, Any]) -> Extractor
        :param item: Extractor description.
        :return: Extractor object.
        :raise ValueError: When reducer or transformer names are unknown.
        r«   NzUnknown transformerr¬   r‰   ÚreducezUnknown reducer©r«   r¬   ÚitemsÚsection)r·   r«   r¬   )ri   ÚtransformersÚ
ValueErrorÚreducersÚPathÚRuleÚfrom_mapÚRules)ÚitemÚtransformerr«   r¬   r‰   Úreducerr´   Ú	extractorr¶   ÚiÚruless              r   r½   zExtractor.from_mapz  s  € ð —h‘h˜{Ó+ˆØÐØ‰Iä$×(Ñ(¨Ó5ˆIØÐ Ü Ð!6Ó7Ð7à—(‘(˜9Ó%ˆà�x‰x˜ÓˆØÐØ—h‘h˜xÓ(ˆGØˆØ‘ä!Ÿ™ gÓ.�Ø�>Ü$Ð%6Ó7Ð7Ü˜T 6°YÈÔPˆIð Ðð —H‘H˜WÓ%ˆEà/4Ö5¨!”T—]‘] 1Õ%Ð5ˆEÐ5Ü˜e¨T¯X©X°iÓ-@Ø(1¸7ôDˆIð Ðùò	 6s   Â;C9rn   )T)	ro   rp   rq   rr   r9   r¯   r²   Ústaticmethodr½   r¤   r-   r   r©   r©   T  s+   „ ÙIóCòTóJð ñ#ó ñ#r-   r©   c                   ó*   ‡ — e Zd ZdZdˆ fd„	Zd„ Zˆ xZS )r»   z4An extractor for getting text out of an XML element.c                 óº   •— t         rt        j                  | ||¬«       nt        ‰| �	  ||¬«       t	        |«      | _        	 |€t        j                  }|| _        y)aÚ  Initialize this extractor.

        :sig: (
                str,
                Optional[Reducer],
                Optional[PathTransformer],
                Optional[str]
            ) -> None
        :param path: Path to apply to get the data.
        :param reduce: Function to reduce selected texts into a single string.
        :param transform: Function to transform extracted value.
        :param foreach: Path to apply for generating a collection of data.
        rµ   N)	r8   r©   r9   r:   r�   r‰   rº   Úconcatr´   )r@   r‰   r´   r«   r¬   rA   s        €r   r9   zPath.__init__¤  sU   ø€ õ Ü×Ñ˜t¨yÀ'ÐÕJä‰GÑ y¸'ÐÔBä˜$“KˆŒ	Ø7àˆ>Ü—_‘_ˆFàˆŒØEr-   c                 ón   — | j                  |«      }t        |«      dk(  rd}|S | j                  |«      }|S )z©Apply this extractor to an element.

        :sig: (Element) -> str
        :param element: Element to apply this extractor to.
        :return: Extracted text.
        r   N)r‰   r!   r´   )r@   r†   ÚselectedrL   s       r   r¯   z
Path.applyÀ  s?   € ð —9‘9˜WÓ%ˆÜˆx‹=˜AÒàˆEð
 ˆð —K‘K Ó)ˆEàˆr-   ©NNN©ro   rp   rq   rr   r9   r¯   rs   rt   s   @r   r»   r»   ¡  s   ø„ Ù>õFö8r-   r»   c                   ó*   ‡ — e Zd ZdZdˆ fd„	Zd„ Zˆ xZS )r¾   z:An extractor for getting data items out of an XML element.c                 óª   •— t         rt        j                  | ||¬«       nt        ‰| �	  ||¬«       || _        	 |�t        |«      | _        yd| _        y)aÎ  Initialize this extractor.

        :sig:
            (
                Sequence[Rule],
                str,
                Optional[MapTransformer],
                Optional[str]
            ) -> None
        :param rules: Rules for generating the data items.
        :param section: Path for setting the root of this section.
        :param transform: Function to transform extracted value.
        :param foreach: Path for generating multiple items.
        rµ   N)r8   r©   r9   r:   rÄ   r�   r·   )r@   rÄ   r·   r«   r¬   rA   s        €r   r9   zRules.__init__Ö  sZ   ø€ õ Ü×Ñ˜t¨yÀ'ÐÕJä‰GÑ y¸'ÐÔBàˆŒ
Ø2à)0Ð)<”u˜W“~ˆŒØHð CGˆŒØHr-   c                 ó¦  — | j                   €|}nx| j                  |«      }t        |«      dk(  rt        j                  d«       t        S t        |«      dkD  rt        d«      ‚|d   }t        j                  d|j                  «       i }| j                  D ]$  }|j                  |«      }|j                  |«       Œ& t        |«      dkD  r|S t        S )z¹Apply this extractor to an element.

        :sig: (Element) -> Mapping[str, Any]
        :param element: Element to apply the extractor to.
        :return: Extracted mapping.
        r   zNo section root foundrš   z.Section path should select exactly one elementzMoving root to %s element)
r·   r!   r#   r$   r±   r¹   r(   rÄ   r²   Úupdate)r@   r†   ÚsubrootÚsubrootsre   ÚruleÚ	extracteds          r   r¯   zRules.applyð  s¼   € ð �<‰<ÐØ‰Gà—|‘| GÓ,ˆHÜ�8‹} Ò!Ü—‘Ð5Ô6Ü�Ü�8‹}˜qÒ Ü Ð!QÓRÐRØ˜q‘kˆGÜ�M‰MÐ5°w·{±{ÔCàˆØ—J‘Jò 	#ˆDØŸ™ WÓ-ˆIØ�K‰K˜	Õ"ð	#ô ˜4“y 1’}ˆtÐ0¬&Ð0r-   rË   rÌ   rt   s   @r   r¾   r¾   Ó  s   ø„ ÙDõIö41r-   r¾   c                   ó.   — e Zd ZdZdd„Zed„ «       Zd„ Zy)r¼   z?A rule describing how to get a data item out of an XML element.Nc                 óX   — || _         	 || _        	 |�t        |«      | _        yd| _        y)a"  Initialize this rule.

        :sig: (Union[str, Extractor], Extractor, Optional[str]) -> None
        :param key: Name to distinguish this data item.
        :param extractor: Extractor that will generate this data item.
        :param foreach: Path for generating multiple items.
        N)ÚkeyrÂ   r�   r¬   )r@   r×   rÂ   r¬   s       r   r9   zRule.__init__  s9   € ð ˆŒØ1à"ˆŒØ:à)0Ð)<”u˜W“~ˆŒØ<ð CGˆŒØ<r-   c                 óÄ   — | d   }t        |t        «      r|nt        j                  |«      }t        j                  | d   «      }t	        ||| j                  d«      ¬«      S )z Generate a rule from a description map.

        :sig: (Mapping[str, Any]) -> Rule
        :param item: Item description.
        :return: Rule object.
        r×   rL   r¬   )r×   rÂ   r¬   )rc   Ústrr©   r½   r¼   ri   )r¿   Úitem_keyr×   rL   s       r   r½   zRule.from_map  sT   € ð ˜‘;ˆÜ$ X¬sÔ3‰h¼×9KÑ9KÈHÓ9UˆÜ×"Ñ" 4¨¡=Ó1ˆÜ˜ u°d·h±h¸yÓ6IÔJÐJr-   c                 óÞ  — i }| j                   €|gn| j                  |«      }|D �]:  }t        | j                  t        «      r| j                  n| j                  j	                  |«      }|€ŒH| j
                  j                   €,| j
                  j	                  |«      }|�|t        u rŒ„|||<   ŒŠ| j
                  j                  |«      D �cg c]  }| j
                  j	                  |d¬«      ‘Œ! }}|D �	cg c]  }	|	€Œ|	t        usŒ|	‘Œ }
}	t        |
«      dk(  rŒ÷| j
                  j                  €|
n(t        t        | j
                  j                  |
«      «      ||<   �Œ= |S c c}w c c}	w )zÁExtract data out of an element using this rule.

        :sig: (Element) -> Mapping[str, Any]
        :param element: Element to extract the data from.
        :return: Extracted data.
        F)r«   r   )r¬   rc   r×   rÙ   r²   rÂ   r±   r!   r«   ÚlistÚmap)r@   r†   re   rÒ   rÑ   r×   rL   r–   Ú
raw_valuesÚvÚvaluess              r   r²   zRule.extract+  sY  € ð ˆØ $§¡Ð 4�G‘9¸$¿,¹,ÀwÓ:OˆØó 	@ˆGô )¨¯©´3Ô7�$—(’(¸T¿X¹X×=MÑ=MÈgÓ=VˆCØˆ{àð �~‰~×%Ñ%Ð-ØŸ™×.Ñ.¨wÓ7�Ø�M u´¡àØ!��S’	ð
 (,§~¡~×'=Ñ'=¸gÓ'FöHØ"#ð #Ÿn™n×4Ñ4°QÀ%Ð4ÕHð H�
ð Hà%/ÖY °A±MÈÔQWÊš!ÐY�ÐYÜ�v“; !Ò#àØ&*§n¡n×&>Ñ&>Ð&F™FÜœ˜TŸ^™^×5Ñ5°vÓ>Ó?ð �S“	ð1	@ð6 ˆùòHùâYs   Ã$E%Ã6E*Ã>E*ÄE*r‘   )ro   rp   rq   rr   r9   rÅ   r½   r²   r¤   r-   r   r¼   r¼   
  s%   „ ÙIó=ð" ñ
Kó ð
Kó$r-   r¼   c                 ó
  — t         rt        j                  j                  }n^| j                  j                  d«      }|€A| j                  «       D ��ci c]  }|D ]  }||“Œ Œ c}}j
                  }|| j                  d<    t        |«      | «      }t        j                  dt        |«      |«       t        |«      dkD  r?|D ]9  }t        j                  d|j                  «        ||«      j                  |«       Œ; yyc c}}w )z²Remove selected elements from the tree.

    :sig: (Element, str) -> None
    :param root: Root element of the tree.
    :param path: XPath to select the elements to remove.
    Ú_get_parentNz%removing %s elements using path: "%s"r   zremoving element: "%s")Ú	_USE_LXMLr   Ú_ElementÚ	getparentr’   ri   Úiterr�   r#   r$   r!   r(   Úremove)Úrootr‰   Ú
get_parentr¦   r‡   Úelementsr†   s          r   Úremove_elementsrë   R  sÝ   € õ Ü ×)Ñ)×3Ñ3‰
ð —[‘[—_‘_ ]Ó3ˆ
ØÐØ(,¯	©	«×? 1¸QÒ?¸˜!˜Q™$Ð?˜!Ó?×CÑCˆJØ)3ˆD�K‰K˜Ñ&ØŒu�T‹{˜4Ó €HÜ‡M�MÐ9¼3¸x»=È$ÔOÜ
ˆ8ƒ}�qÒØò 	0ˆGÜ�M‰MÐ2°G·K±KÔ@á�wÓ×&Ñ& wÕ/ñ	0ð ùó	 @s   ÁC?c                 ó:  —  t        |«      | «      }t        j                  dt        |«      |«       |D ]å  }t	        |t
        «      r|n#t        j                  |«      j                  |«      }|€!t        j                  d|j                  «       Œ\t	        |t
        «      r|n#t        j                  |«      j                  |«      }|€!t        j                  d|j                  «       Œµt        j                  d|||j                  «       ||j                  |<   Œç y)a¤  Set an attribute for selected elements.

    :sig:
        (
            Element,
            str,
            Union[str, Mapping[str, Any]],
            Union[str, Mapping[str, Any]]
        ) -> None
    :param root: Root element of the tree.
    :param path: XPath to select the elements to set attributes for.
    :param name: Description for name generation.
    :param value: Description for value generation.
    ú%updating %s elements using path: "%s"Nz,no attribute name generated for "%s" elementz-no attribute value generated for "%s" elementz.setting "%s" attribute to "%s" on "%s" element)r�   r#   r$   r!   rc   rÙ   r©   r½   r²   r(   r’   )rè   r‰   rK   rL   rê   r†   rW   rX   s           r   Úset_element_attrrî   j  sì   € ð Œu�T‹{˜4Ó €HÜ‡M�MÐ9¼3¸x»=È$ÔOØò /ˆÜ& t¬SÔ1‘DÜ×Ñ˜tÓ$×,Ñ,¨WÓ5ð 	àÐÜ�M‰MÐHÈ'Ï+É+ÔVØä(¨´Ô4‘UÜ×Ñ˜uÓ%×-Ñ-¨gÓ6ð 	àÐÜ�M‰MÐIÈ7Ï;É;ÔWØä�‰ÐFØ ¨W¯[©[ô	:à$.ˆ�‰�yÒ!ñ/r-   c                 ó0  —  t        |«      | «      }t        j                  dt        |«      |«       |D ]`  }t	        |t
        «      r|n#t        j                  |«      j                  |«      }t        j                  d||j                  «       ||_
        Œb y)a  Set the text for selected elements.

    :sig: (Element, str, Union[str, Mapping[str, Any]]) -> None
    :param root: Root element of the tree.
    :param path: XPath to select the elements to set attributes for.
    :param text: Description for text generation.
    rí   z$setting text to "%s" on "%s" elementN)r�   r#   r$   r!   rc   rÙ   r©   r½   r²   r(   rŒ   )rè   r‰   rŒ   rê   r†   Úelement_texts         r   Úset_element_textrñ   �  s€   € ð Œu�T‹{˜4Ó €HÜ‡M�MÐ9¼3¸x»=È$ÔOØò $ˆÜ)¨$´Ô4‘tÜ×Ñ˜tÓ$×,Ñ,¨WÓ5ð 	ô 	�‰Ð<¸lÈGÏKÉKÔXØ#ˆ�ñ$r-   c                 óÖ   — t         r| j                  d«      n| }t        r6|r4t        j	                  d«       ddl}|j                  j                  |«      S t        j                  |«      S )züBuild a tree from an XML document.

    :sig: (str, Optional[bool]) -> Element
    :param document: XML document to build the tree from.
    :param force_html: Force to parse from HTML without converting.
    :return: Root element of the XML tree.
    rb   zusing lxml html builderr   N)	r8   Úencoderã   r#   ÚinfoÚ	lxml.htmlÚhtmlÚ
fromstringr   )rx   Ú
force_htmlr%   r|   s       r   Ú
build_treerù   Ÿ  sQ   € õ +.ˆh�o‰o˜gÔ&°8€GÝ‘ZÜ�‰Ð.Ô/ÛØ�y‰y×#Ñ# GÓ,Ð,Ü×!Ñ! 'Ó*Ð*r-   c                   ó"   — e Zd ZdZd„ Zd„ Zd„ Zy)ÚRegistryz$A simple, attribute-based namespace.c                 ó:   — | j                   j                  |«       y)z†Initialize this registry.

        :sig: (Mapping[str, Any]) -> None
        :param entries: Entries to add to this registry.
        N)Ú__dict__rÐ   )r@   Úentriess     r   r9   zRegistry.__init__²  s   € ð 	�‰×Ñ˜WÕ%r-   c                 ó8   — | j                   j                  |«      S )z¤Get the value of an entry from this registry.

        :sig: (str) -> Any
        :param item: Entry to get the value for.
        :return: Value of entry.
        )rý   ri   )r@   r¿   s     r   ri   zRegistry.getº  s   € ð �}‰}× Ñ  Ó&Ð&r-   c                 ó"   — || j                   |<   y)zÃRegister a new entry in this registry.

        :sig: (str, Any) -> None
        :param key: Key to search the entry in this registry.
        :param value: Value to store for the entry.
        N)rý   )r@   r×   rL   s      r   ÚregisterzRegistry.registerÃ  s   € ð #ˆ�‰�cÒr-   N)ro   rp   rq   rr   r9   ri   r  r¤   r-   r   rû   rû   ¯  s   „ Ù.ò&ò'ó#r-   rû   )rç   Úset_attrÚset_textrD   c                 óŠ   — t        j                  dddj                  | «      j                  dd«      «      j	                  «       S )Nz\s+rM   rD   õ   Â )ÚreÚsubrT   ÚreplaceÚstrip©Úxss    r   r§   r§   Ú  s1   € œŸ™˜v s¨B¯G©G°B«K×,?Ñ,?ÀÈÓ,LÓM×SÑSÓU€ r-   c                 óŠ   — t        j                  dddj                  | «      j                  «       j	                  dd«      «      S )Nz
[^a-z0-9_]rD   rM   Ú_)r  r  rT   Úlowerr  r
  s    r   r§   r§   Û  s3   € œBŸF™F <°°R·W±W¸R³[×5FÑ5FÓ5H×5PÑ5PÐQTÐVYÓ5ZÓ[€ r-   )ÚfirstrÈ   ÚcleanÚ	normalize)
ÚintÚfloatÚboolr!   r  ÚupperÚ
capitalizeÚlstripÚrstripr	  c                 óÊ   — |D ]^  }|d   }|dk(  rt        | |d   «       Œ|dk(  rt        | |d   |d   |d   ¬«       Œ;|dk(  rt        | |d   |d	   ¬
«       ŒUt        d«      ‚ y)zËProcess a tree before starting extraction.

    :sig: (Element, Sequence[Mapping[str, Any]]) -> None
    :param root: Root of tree to process.
    :param pre: Descriptions for processing operations.
    Úoprç   r‰   r  rK   rL   rJ   r  rŒ   )rŒ   zUnknown preprocessing operationN)rë   rî   rñ   r¹   )rè   ÚpreÚstepr  s       r   Ú
preprocessr  ó  s}   € ð ò 	@ˆØ�$‰ZˆØ�Š>Ü˜D $ v¡,Õ/Ø�:ÒÜ˜T 4¨¡<°d¸6±lÈ$ÈwÉ-ÖXØ�:ÒÜ˜T 4¨¡<°d¸6±lÖCäÐ>Ó?Ð?ñ	@r-   c                 óŠ   — t        |D �cg c]  }t        j                  |«      ‘Œ c}|¬«      }|j                  | «      S c c}w )a  Extract data from an XML element.

    :sig:
        (
            Element,
            Sequence[Mapping[str, Any]],
            Optional[str]
        ) -> Mapping[str, Any]
    :param element: Element to extract the data from.
    :param items: Descriptions for extracting items.
    :param section: Path to select the root element for these items.
    :return: Extracted data.
    ©r·   )r¾   r¼   r½   r²   )r†   r¶   r·   r¿   rÄ   s        r   r²   r²     s8   € ô °5Ö9¨4”4—=‘= Õ&Ò9À7ÔK€EØ�=‰=˜Ó!Ð!ùò :s   ŠA c                 ó²   — t        | «      }|j                  d«      }|�t        ||«       t        ||j                  d«      |j                  d«      ¬«      }|S )zîExtract data from a document after optionally preprocessing it.

    :sig: (str, Mapping[str, Any]) -> Mapping[str, Any]
    :param document: Document to scrape.
    :param spec: Extraction specification.
    :return: Extracted data.
    r  r¶   r·   r  )rù   ri   r  r²   )rx   Úspecrè   r  re   s        r   Úscraper"    sO   € ô �hÓ€DØ
�(‰(�5‹/€CØ
€Ü�4˜ÔÜ�4˜Ÿ™ 'Ó*°D·H±H¸YÓ4GÔH€DØ€Kr-   c                 ó|  — | dk(  r4t         j                  d«       t        j                  j	                  «       }nat         j                  dt
        j                  j                  | «      «       t        | d«      5 }t        |j	                  «       «      }ddd«       t        t        «      d¬«       y# 1 sw Y   Œ xY w)zyConvert an HTML file into XHTML and print.

    :sig: (str) -> None
    :param source: Path of HTML file to convert.
    ú-zreading from stdinzreading from file: "%s"ÚrbNrD   rE   )r#   r$   r   ÚstdinÚreadÚosr‰   ÚabspathÚopenr,   rQ   r{   )Úsourcer%   Úfs      r   Úh2xr-  -  s„   € ð �‚}Ü�‰Ð*Ô+Ü—)‘)—.‘.Ó"‰ä�‰Ð/´·±·±ÀÓ1HÔIÜ�&˜$Óð 	, 1Ü! !§&¡&£(Ó+ˆG÷	,ä	Œ-˜Ó
  bÖ)÷	,ð 	,ús   Á9B2Â2B;c                 óÂ  — t         j                  dt        j                  j	                  |«      «       t        j                  j                  |«      d   dk(  r't        d«      €t        d«      ‚ddl}|j                  }nt        j                  }t        |«      5 } ||j                  «       «      }ddd«       | j                  d«      r;t         j                  d	| «       t        | «      5 }|j                  «       }ddd«       nXt         j                  d
t        j                  j	                  | «      «       t        | d«      5 }|j                  «       }ddd«       t!        «      }|dk(  r t         j                  d«       t#        |«      }t%        |«      }	t'        t        j(                  |	dd¬«      «       y# 1 sw Y   �ŒxY w# 1 sw Y   ŒtxY w# 1 sw Y   Œ€xY w)a  Scrape data from a file path or a URL and print.

    :sig: (str, str, Optional[str]) -> None
    :param address: File path or URL of document to scrape.
    :param spec: Path of spec file.
    :param content_format: Whether the content is XML or HTML.
    zloading spec from file: "%s"rH   z.yamlÚyamlNzYAML support not availabler   )zhttp://zhttps://zloading url: "%s"zloading file: "%s"r%  rö   z!converting html document to xhtmlé   T)ÚindentÚ	sort_keys)r#   r$   r(  r‰   r)  Úsplitextr   ÚRuntimeErrorr/  ÚloadÚjsonÚloadsr*  r'  r�   r   r,   r{   r"  rQ   Údumps)
Úaddressr!  Úcontent_formatr/  Úspec_loaderr,  Úspec_mapr%   rx   re   s
             r   Úscrape_documentr=  =  s{  € ô ‡M�MÐ0´"·'±'·/±/À$Ó2GÔHÜ	‡w�w×Ñ˜Ó˜bÑ! WÒ,Ü�vÓÐ&ÜÐ;Ó<Ð<ÛØ—i‘i‰ä—j‘jˆä	ˆd‹ð )�qÙ˜qŸv™v›xÓ(ˆ÷)ð ×ÑÐ1Ô2Ü�‰Ð)¨7Ô3Ü�WÓð 	 Ø—f‘f“hˆG÷	ð 	ô 	�‰Ð*¬B¯G©G¯O©O¸GÓ,DÔEÜ�'˜4Ó ð 	 AØ—f‘f“hˆG÷	ä˜7Ó#€Hà˜ÒÜ�‰Ð9Ô:Ü  Ó*ˆô �(˜HÓ%€DÜ	Œ$�*‰*�T !¨tÔ
4Õ5÷')ñ )ú÷
	ð 	ú÷	ð 	ús$   ÂF<Ã,G	ÅGÆ<GÇ	GÇGc                 óØ  — t        | ¬«      }|j                  ddd¬«       |j                  ddd¬	«       |j                  d
d
¬«      }d|_        |j	                  dd¬«      }|j                  dd¬«       |j                  d„ ¬«       |j	                  dd¬«      }|j                  dd¬«       |j                  dddd¬«       |j                  ddd¬	«       |j                  d„ ¬«       |S )z—Build a parser for command line arguments.

    :sig: (str) -> ArgumentParser
    :param prog: Name of program.
    :return: Parser for arguments.
    ©Úprogz	--versionÚversionz%(prog)s 1.0b7)ÚactionrA  z--debugÚ
store_truezenable debug messages)rB  ÚhelpÚcommand)ÚmetavarÚdestTr-  zconvert HTML to XHTML)rD  Úfilezfile to convertc                 ó,   — t        | j                  «      S r‘   )r-  rH  ©Úas    r   r§   zmake_parser.<locals>.<lambda>t  s   € ¬3¨q¯v©v«;€ r-   )Úfuncr"  zscrape a documentrx   z&file path or URL of document to scrapez-sz--specz	spec file)ÚrequiredrD  z--htmlzdocument is in HTML formatc                 ól   — t        | j                  | j                  | j                  rd¬«      S d¬«      S )Nrö   Úxml)r:  )r=  rx   r!  rö   rJ  s    r   r§   zmake_parser.<locals>.<lambda>z  s*   € ¬oØ	�
‰
�A—F‘F°Q·V²V¨6ô/€ ØAFô/€ r-   )r   Úadd_argumentÚadd_subparsersrM  Ú
add_parserÚset_defaults)r@  ÚparserÚcommandsÚ
h2x_parserÚscrape_parsers        r   Úmake_parserrX  d  s  € ô  Ô&€FØ
×Ñ˜¨IÐ?OÐÔPØ
×Ñ˜	¨,Ð=TÐÔUà×$Ñ$¨Y¸YÐ$ÓG€HØ€HÔà×$Ñ$ UÐ1HÐ$ÓI€JØ×Ñ˜FÐ):ÐÔ;Ø×ÑÑ!6ÐÔ7à×'Ñ'¨Ð7JÐ'ÓK€MØ×Ñ˜zÐ0XÐÔYØ×Ñ˜t X¸À;ÐÔOØ×Ñ˜x°ÐC_ÐÔ`Ø×Ññ %Ðô ð €Mr-   c                 ó¦  — | �| nt         j                  } t        d¬«      }|j                  | dd «      }|j                  r9t
        j                  t
        j                  ¬«       t        j	                  d«       	 |j                  |«       y# t        $ r:}t        |t         j                  ¬«       t        j                  d«       Y d}~yd}~ww xY w)zEntry point of the command line utility.

    :sig: (Optional[List[str]]) -> None
    :param argv: Command line arguments.
    Nr   r?  rš   )Úlevelzrunning in debug mode)rH  )r   ÚargvrX  Ú
parse_argsr$   ÚloggingÚbasicConfigÚDEBUGr#   rL  Ú	ExceptionrQ   ÚstderrÚexit)r[  rT  Ú	argumentsr‡   s       r   Úmainrd  �  s›   € ð Ð#‰4¬¯©€DÜ˜iÔ(€FØ×!Ñ! $ q r (Ó+€Ið ‡‚Ü×Ñ¤'§-¡-ÐÔ0Ü�‰Ð-Ô.ðØ�‰�yÕ!øÜò Üˆa”c—j‘jÕ!Ü�‰��‰ûðús   Á;B Â	CÂ0CÃCÚ__main__)Nrb   rn   )Fr‘   )rO  )`rr   Ú
__future__r   r   r   r   r6  r(  r  r   Úargparser   Úcollectionsr   Ú	functoolsr	   Úoperatorr
   Úpkgutilr   Úversion_infor8   ÚunicoderÙ   rd   Úcgir   rS   r   r   Úhtmlentitydefsr   Úurllib2r   rö   Úhtml.parserÚioÚurllib.requestÚ
contextlibr   r   Úimdb.parser.http.loggingr   ÚgetChildr#   r   r,   r/   r{   rã   rô   r|   r}   r   Ú
lxml.etreer~   r�   rä   ÚxpathÚ	xml.etreeÚxml.etree.ElementTreer±   r©   r»   r¾   r¼   rë   rî   rñ   rù   rû   Ú_PREPROCESSORSÚpreprocessorsrT   Ú	_REDUCERSrº   r  r  r  r!   r  r  r  r  r  r	  Ú_TRANSFORMERSr¸   r  r²   r"  r-  r=  rX  rd  ro   r¤   r-   r   ú<module>r     sZ  ðñ ÷ SÓ Rã Û 	Û 	Û 
Ý #Ý Ý Ý Ý ð 
×Ñ˜Ñ€ñ Ø˜#€J€Cˆñ Ý)Ý%Ý!Ý-Þå*Ý&ÝÝ&ñ Ý)àñ$ó ñ$õ +å +à
ˆ&�/‰/˜)Ó
$€ð DØð€ó#ô8m4�Zô m4ólñ0 ˜Ó tÐ+€	ÙØ‡L�L�ÔÝ)Ý"à×Ñ€EØ× Ñ ×&Ñ&�Eå%Ý-÷5(ñ 5(ñn %€Eð 
€÷Jñ JôZ/ˆ9ô /ôd41ˆIô 41÷nEñ EòP0ò0 /òF$ó$+÷ #ñ #ð> Ø Ø ñ€ñ ˜Ó(€Ø ñ ˜‹]Ù�c—h‘h Ó#ÙUÙ[ñ	€	ñ �IÓ€Ø ð ØØØØ�Y‰YØ�Y‰YØ—.‘.Ø�j‰jØ�j‰jØ�Y‰Yñ€ñ ˜Ó&€Ø ò@ó&"ò$ò**ó $6òNó:ð. ˆzÒÙ…Fð r-   