B `> @s2dZyddlmZWn.ek rBZzddlmZWddZ[XYnXddlZddlZddlZy ddl Z Wn0ek rZzdZ e dWddZ[XYnXddl m Z m Z mZdZejddkZedZed Zd d Zed d ddddddddddg ZGdddeZGdddeZGdddeZGdddeZGd d!d!eZGd"d#d#eeZGd$d%d%eZ Gd&d'd'e Z!Gd(d)d)e Z"Gd*d+d+e"Z#Gd,d-d-e Z$Gd.d/d/e Z%Gd0d1d1e Z&Gd2d3d3eZ'Gd4d5d5eZ(Gd6d7d7eZ)Gd8d9d9eZ*Gd:d;d;eZ+GdMIT)CallableNzEThe soupsieve package is not installed. CSS selectors cannot be used.) Formatter HTMLFormatter XMLFormatterzutf-8z\S+z\s+cs&tfdd}|jfdd}|S)z>Alias one attribute name to another for backward compatibilitycs t|S)N)getattr)self)attrk/private/var/folders/fw/jsxvvqfs4sz4tdnfdvg5typ5vk77qg/T/pip-install-p7nfy4dm/beautifulsoup4/bs4/element.pyalias$sz_alias..aliascs t|S)N)setattr)r )r r r r (s)propertysetter)r r r )r r _alias"sridnambcsZoemZpalmospunycodeZraw_unicode_escapeZ undefinedZunicode_escapezraw-unicode-escapezunicode-escapez string-escapeZ string_escapec@seZdZdZdddZdS)NamespacedAttributezA namespaced string (e.g. 'xml:lang') that remembers the namespace ('xml') and the name ('lang') that were used to create it. NcCs^|sd}|dkrt||}n*|dkr4t||}nt||d|}||_||_||_|S)N:)str__new__prefixname namespace)clsrrrobjr r r rPszNamespacedAttribute.__new__)NN)__name__ __module__ __qualname____doc__rr r r r rKsrc@seZdZdZdS)%AttributeValueWithCharsetSubstitutionz=A stand-in object for a character encoding specified in HTML.N)rrr r!r r r r r"bsr"c@s eZdZdZddZddZdS)CharsetMetaAttributeValuezA generic stand-in for the value of a meta tag's 'charset' attribute. When Beautiful Soup parses the markup '', the value of the 'charset' attribute will be one of these objects. cCst||}||_|S)N)rroriginal_value)rr$rr r r rls z!CharsetMetaAttributeValue.__new__cCs|tkr dS|S)zWhen an HTML document is being encoded to a given encoding, the value of a meta tag's 'charset' is the name of the encoding. )PYTHON_SPECIFIC_ENCODINGS)r encodingr r r encodeqsz CharsetMetaAttributeValue.encodeN)rrr r!rr(r r r r r#esr#c@s.eZdZdZedejZddZddZ dS)ContentMetaAttributeValueaA generic stand-in for the value of a meta tag's 'content' attribute. When Beautiful Soup parses the markup: The value of the 'content' attribute will be one of these objects. z((^|;)\s*charset=)([^;]*)cCs6|j|}|dkr tt|St||}||_|S)N) CHARSET_REsearchrrr$)rr$matchrr r r rs    z!ContentMetaAttributeValue.__new__cs(tkr dSfdd}|j||jS)Nr%cs|dS)N)group)r,)r'r r rewritesz1ContentMetaAttributeValue.encode..rewrite)r&r*subr$)r r'r/r )r'r r(s z ContentMetaAttributeValue.encodeN) rrr r!recompileMr*rr(r r r r r)zs r)c@s eZdZdZdTddZddZddZed d Ze d Z e d Z d dZ e Z ddZeZeZddZdUddZdVddZeZddZddZddZddZd d!Zdidfd"d#ZeZdiddfd$d%ZeZdidfd&d'ZeZdiddfd(d)Z e Z!e Z"didfd*d+Z#e#Z$diddfd,d-Z%e%Z&e%Z'didfd.d/Z(e(Z)diddfd0d1Z*e*Z+e*Z,difd2d3Z-e-Z.didfd4d5Z/e/Z0e/Z1ed6d7Z2ed8d9Z3d:d;Z4dd?Z6ed@dAZ7edBdCZ8edDdEZ9edFdGZ:edHdIZ;dJdKZdPdQZ?dRdSZ@dS)W PageElementzContains the navigational information for some part of the page: that is, its current location in the parse tree. NavigableString, Tag, etc. are all subclasses of PageElement. NcCs||_||_|dk r||j_||_|jdk r4||j_||_|jdk rL||j_|dkrr|jdk rr|jjrr|jjd}||_|dk r||j_dS)aRSets up the initial relations between this element and other elements. :param parent: The parent of this element. :param previous_element: The element parsed immediately before this one. :param next_element: The element parsed immediately before this one. :param previous_sibling: The most recently encountered element on the same level of the parse tree as this one. :param previous_sibling: The next element to be encountered on the same level of the parse tree as this one. N)parentprevious_element next_element next_siblingprevious_siblingcontents)r r6r7r8r:r9r r r setups    zPageElement.setupcCs.|dkr |St|ts ||}||}|S)zFormat the given string using the given formatter. :param s: A string. :param formatter: A Formatter object, or a string naming one of the standard formatters. N) isinstancerformatter_for_name substitute)r s formatteroutputr r r format_strings    zPageElement.format_stringcCs<t|tr|S|jrt}nt}t|tr2||dS|j|S)a|Look up or create a Formatter for the given identifier, if necessary. :param formatter: Can be a Formatter object (used as-is), a function (used as the entity substitution hook for an XMLFormatter or HTMLFormatter), or a string (used to look up an XMLFormatter or HTMLFormatter in the appropriate registry. )Zentity_substitution)r=r_is_xmlrrrZREGISTRY)r rAcr r r r>s   zPageElement.formatter_for_namecCs.|jdk r|jS|jdkr&t|ddS|jjS)aIs this element part of an XML tree or an HTML tree? This is used in formatter_for_name, when deciding whether an XMLFormatter or HTMLFormatter is more appropriate. It can be inefficient, but it should be called very rarely. Nis_xmlF) known_xmlr6rrD)r r r r rDs    zPageElement._is_xmlr9r:cCs^|jdkrtd||krdS||jkr0td|j}|j|}|j|d||||S)zReplace this PageElement with another one, keeping the rest of the tree the same. :param replace_with: A PageElement. :return: `self`, no longer part of the tree. Nz^Cannot replace one element with another when the element to be replaced is not part of a tree.z%Cannot replace a Tag with its parent.) _self_index)r6 ValueErrorindexextractinsert)r replace_withZ old_parentmy_indexr r r rMs     zPageElement.replace_withcCs\|j}|jdkrtd|j|}|j|dx&t|jddD]}|||qDW|S)zjReplace this PageElement with its contents. :return: `self`, no longer part of the tree. NzSCannot replace an element with its contents when thatelement is not part of a tree.)rH)r6rIrJrKreversedr;rL)r Z my_parentrNchildr r r unwraps   zPageElement.unwrapcCs||}|||S)zWrap this PageElement inside another one. :param wrap_inside: A PageElement. :return: `wrap_inside`, occupying the position in the tree that used to be occupied by `self`, and with `self` inside it. )rMappend)r Z wrap_insidemer r r wrap*s  zPageElement.wrapcCs|jdk r(|dkr|j|}|jj|=|}|j}|jdk rR|j|k rR||j_|dk rl||jk rl|j|_d|_d|_d|_|jdk r|j|jk r|j|j_|jdk r|j|jk r|j|j_d|_|_|S)aDestructively rips this element out of the tree. :param _self_index: The location of this element in its parent's .contents, if known. Passing this in allows for a performance optimization. :return: `self`, no longer part of the tree. N)r6rJr;_last_descendantr8r7r:r9)r rH last_childr8r r r rK5s,            zPageElement.extractTcCsP|r|jdk r|jj}n$|}xt|tr:|jr:|jd}qW|sL||krLd}|S)zFinds the last element beneath this object to be parsed. :param is_initialized: Has `setup` been called on this PageElement yet? :param accept_self: Is `self` an acceptable answer to the question? Nr5)r9r7r=Tagr;)r Zis_initializedZ accept_selfrVr r r rU[s  zPageElement._last_descendantc Cs|dkrtd||kr tdt|trsz,PageElement.insert_before..z&Can't insert an element before itself.)r6rIanyr=r4rKrJrL)r argsr6Z predecessorrJr )r r insert_befores   zPageElement.insert_beforecsj}|dkrtdtfdd|Dr4tdd}xD|D]<}t|trT||}||d|||d7}q>WdS)zMakes the given element(s) the immediate successor of this one. The elements will have the same parent, and the given elements will be immediately after this one. :param args: One or more PageElements. Nz1Element has no parent, so 'after' has no meaning.c3s|]}|kVqdS)Nr )rcrd)r r r resz+PageElement.insert_after..z%Can't insert an element after itself.rr-)r6rIrfr=r4rKrJrL)r rgr6offset successorrJr )r r insert_afters    zPageElement.insert_aftercKs|j|j|||f|S)aSFind the first PageElement that matches the given criteria and appears later in the document than this PageElement. All find_* methods take a common set of arguments. See the online documentation for detailed explanations. :param name: A filter on tag name. :param attrs: A dictionary of filters on attribute values. :param text: A filter for a NavigableString with specific text. :kwargs: A dictionary of filters on attribute values. :return: A PageElement. :rtype: bs4.element.Tag | bs4.element.NavigableString ) _find_one find_all_next)r rattrstextkwargsr r r find_nextszPageElement.find_nextcKs|j|||||jf|S)agFind all PageElements that match the given criteria and appear later in the document than this PageElement. All find_* methods take a common set of arguments. See the online documentation for detailed explanations. :param name: A filter on tag name. :param attrs: A dictionary of filters on attribute values. :param text: A filter for a NavigableString with specific text. :param limit: Stop looking after finding this many results. :kwargs: A dictionary of filters on attribute values. :return: A ResultSet containing PageElements. ) _find_all next_elements)r rrnrolimitrpr r r rmszPageElement.find_all_nextcKs|j|j|||f|S)aOFind the closest sibling to this PageElement that matches the given criteria and appears later in the document. All find_* methods take a common set of arguments. See the online documentation for detailed explanations. :param name: A filter on tag name. :param attrs: A dictionary of filters on attribute values. :param text: A filter for a NavigableString with specific text. :kwargs: A dictionary of filters on attribute values. :return: A PageElement. :rtype: bs4.element.Tag | bs4.element.NavigableString )rlfind_next_siblings)r rrnrorpr r r find_next_sibling(szPageElement.find_next_siblingcKs|j|||||jf|S)aFind all siblings of this PageElement that match the given criteria and appear later in the document. All find_* methods take a common set of arguments. See the online documentation for detailed explanations. :param name: A filter on tag name. :param attrs: A dictionary of filters on attribute values. :param text: A filter for a NavigableString with specific text. :param limit: Stop looking after finding this many results. :kwargs: A dictionary of filters on attribute values. :return: A ResultSet of PageElements. :rtype: bs4.element.ResultSet )rr next_siblings)r rrnrortrpr r r ru:s zPageElement.find_next_siblingscKs|j|j|||f|S)aTLook backwards in the document from this PageElement and find the first PageElement that matches the given criteria. All find_* methods take a common set of arguments. See the online documentation for detailed explanations. :param name: A filter on tag name. :param attrs: A dictionary of filters on attribute values. :param text: A filter for a NavigableString with specific text. :kwargs: A dictionary of filters on attribute values. :return: A PageElement. :rtype: bs4.element.Tag | bs4.element.NavigableString )rlfind_all_previous)r rrnrorpr r r find_previousOszPageElement.find_previouscKs|j|||||jf|S)aLook backwards in the document from this PageElement and find all PageElements that match the given criteria. All find_* methods take a common set of arguments. See the online documentation for detailed explanations. :param name: A filter on tag name. :param attrs: A dictionary of filters on attribute values. :param text: A filter for a NavigableString with specific text. :param limit: Stop looking after finding this many results. :kwargs: A dictionary of filters on attribute values. :return: A ResultSet of PageElements. :rtype: bs4.element.ResultSet )rrprevious_elements)r rrnrortrpr r r rxaszPageElement.find_all_previouscKs|j|j|||f|S)aTReturns the closest sibling to this PageElement that matches the given criteria and appears earlier in the document. All find_* methods take a common set of arguments. See the online documentation for detailed explanations. :param name: A filter on tag name. :param attrs: A dictionary of filters on attribute values. :param text: A filter for a NavigableString with specific text. :kwargs: A dictionary of filters on attribute values. :return: A PageElement. :rtype: bs4.element.Tag | bs4.element.NavigableString )rlfind_previous_siblings)r rrnrorpr r r find_previous_siblingvsz!PageElement.find_previous_siblingcKs|j|||||jf|S)aReturns all siblings to this PageElement that match the given criteria and appear earlier in the document. All find_* methods take a common set of arguments. See the online documentation for detailed explanations. :param name: A filter on tag name. :param attrs: A dictionary of filters on attribute values. :param text: A filter for a NavigableString with specific text. :param limit: Stop looking after finding this many results. :kwargs: A dictionary of filters on attribute values. :return: A ResultSet of PageElements. :rtype: bs4.element.ResultSet )rrprevious_siblings)r rrnrortrpr r r r{s z"PageElement.find_previous_siblingscKs&d}|j||df|}|r"|d}|S)aFind the closest parent of this PageElement that matches the given criteria. All find_* methods take a common set of arguments. See the online documentation for detailed explanations. :param name: A filter on tag name. :param attrs: A dictionary of filters on attribute values. :kwargs: A dictionary of filters on attribute values. :return: A PageElement. :rtype: bs4.element.Tag | bs4.element.NavigableString Nr-r) find_parents)r rrnrprlr r r find_parents zPageElement.find_parentcKs|j||d||jf|S)aFind all parents of this PageElement that match the given criteria. All find_* methods take a common set of arguments. See the online documentation for detailed explanations. :param name: A filter on tag name. :param attrs: A dictionary of filters on attribute values. :param limit: Stop looking after finding this many results. :kwargs: A dictionary of filters on attribute values. :return: A PageElement. :rtype: bs4.element.Tag | bs4.element.NavigableString N)rrparents)r rrnrtrpr r r r~szPageElement.find_parentscCs|jS)zThe PageElement, if any, that was parsed just after this one. :return: A PageElement. :rtype: bs4.element.Tag | bs4.element.NavigableString )r8)r r r r nextszPageElement.nextcCs|jS)zThe PageElement, if any, that was parsed just before this one. :return: A PageElement. :rtype: bs4.element.Tag | bs4.element.NavigableString )r7)r r r r previousszPageElement.previouscKs&d}||||df|}|r"|d}|S)Nr-rr )r methodrrnrorprrr r r rls zPageElement._find_onec  s0|dkrd|kr|d}|d=ttr.}nt||f|}|dkr|s|s|s̈dksbdkrzdd|D}t||Sttr̈ddkrdd\ndfdd|D}t||St|} xVy t|} Wntk rPYnX| r|| } | r| | |rt | |krPqW| S) z8Iterates over a generator looking for things that match.NstringTcss|]}t|tr|VqdS)N)r=rW)rcelementr r r resz(PageElement._find_all..rr-c3sB|]:}t|tr|jks6|jkrdks6|jkr|VqdS)N)r=rWrr)rcr) local_namerrr r res    ) r= SoupStrainer ResultSetrcountsplitr StopIterationr+rRr\) r rrnrort generatorrpZstrainerresultresultsifoundr )rrrr rrs<       zPageElement._find_allccs$|j}x|dk r|V|j}qWdS)zgAll PageElements that were parsed after this one. :yield: A sequence of PageElements. N)r8)r rr r r rss zPageElement.next_elementsccs$|j}x|dk r|V|j}qWdS)zAll PageElements that are siblings of this one but were parsed later. :yield: A sequence of PageElements. N)r9)r rr r r rw#s zPageElement.next_siblingsccs$|j}x|dk r|V|j}qWdS)zhAll PageElements that were parsed before this one. :yield: A sequence of PageElements. N)r7)r rr r r rz/s zPageElement.previous_elementsccs$|j}x|dk r|V|j}qWdS)zAll PageElements that are siblings of this one but were parsed earlier. :yield: A sequence of PageElements. N)r:)r rr r r r}:s zPageElement.previous_siblingsccs$|j}x|dk r|V|j}qWdS)zlAll PageElements that are parents of this PageElement. :yield: A sequence of PageElements. N)r6)r rr r r rFs zPageElement.parentscCst|ddpdS)zOCheck whether a PageElement has been decomposed. :rtype: bool _decomposedF)r)r r r r decomposedQszPageElement.decomposedcCs|jS)N)rs)r r r r nextGenerator[szPageElement.nextGeneratorcCs|jS)N)rw)r r r r nextSiblingGenerator^sz PageElement.nextSiblingGeneratorcCs|jS)N)rz)r r r r previousGeneratoraszPageElement.previousGeneratorcCs|jS)N)r})r r r r previousSiblingGeneratordsz$PageElement.previousSiblingGeneratorcCs|jS)N)r)r r r r parentGeneratorgszPageElement.parentGenerator)NNNNN)N)TT)Arrr r!r<rCr>rrDrZ nextSiblingZpreviousSiblingrM replaceWithrQZreplace_with_childrenZreplaceWithChildrenrTrKrUZ_lastRecursiveChildrLrRrbrhrkrqZfindNextrmZ findAllNextrvZfindNextSiblingruZfindNextSiblingsZfetchNextSiblingsryZ findPreviousrxZfindAllPreviousZ fetchPreviousr|ZfindPreviousSiblingr{ZfindPreviousSiblingsZfetchPreviousSiblingsrZ findParentr~Z findParentsZ fetchParentsrrrlrrrsrwrzr}rrrrrrrr r r r r4s| (   & R   6 r4c@s`eZdZdZdZdZdZddZddZdd Z d d Z dd dZ e ddZ e jddZ dS)rYzA Python Unicode string that is part of a parse tree. When Beautiful Soup parses the markup penguin, it will create a NavigableString for the string "penguin". r%NcCs2t|trt||}nt||t}||S)a-Create a new NavigableString. When unpickling a NavigableString, this method is called with the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be passed in to the superclass's __new__ or the superclass won't know how to handle non-ASCII characters. )r=rrDEFAULT_OUTPUT_ENCODINGr<)rvalueur r r rzs  zNavigableString.__new__cCs t||S)zA copy of a NavigableString has the same contents and class as the original, but it is not connected to the parse tree. )type)r r r r __copy__szNavigableString.__copy__cCs t|fS)N)r)r r r r __getnewargs__szNavigableString.__getnewargs__cCs$|dkr |Std|jj|fdS)ztext.string gives you text. This is for backwards compatibility for Navigable*String, but for CData* it lets you get the string without the CData wrapper.rz!'%s' object has no attribute '%s'N)AttributeError __class__r)r r r r r __getattr__s zNavigableString.__getattr__minimalcCs|||}|j||jS)zRun the string through the provided formatter. :param formatter: A Formatter object, or a string naming one of the standard formatters. )rCPREFIXSUFFIX)r rArBr r r output_readys zNavigableString.output_readycCsdS)zSince a NavigableString is not a Tag, it has no .name. This property is implemented so that code like this doesn't crash when run on a mixture of Tag and NavigableString objects: [x.name for x in tag.children] Nr )r r r r rszNavigableString.namecCs tddS)z1Prevent NavigableString.name from ever being set.z)A NavigableString cannot be given a name.N)r)r rr r r rs)r)rrr r!rrrGrrrrrrrrr r r r rYks  rYc@s"eZdZdZdZdZdddZdS)PreformattedStringzA NavigableString not subject to the normal formatting rules. This is an abstract class used for special kinds of strings such as comments (the Comment class) and CDATA blocks (the CData class). r%NcCs$|dk r|||}|j||jS)aMake this string ready for output by adding any subclass-specific prefix or suffix. :param formatter: A Formatter object, or a string naming one of the standard formatters. The string will be passed into the Formatter, but only to trigger any side effects: the return value is ignored. :return: The string, with any subclass-specific prefix and suffix added on. N)rCrr)r rAignorer r r rs  zPreformattedString.output_ready)N)rrr r!rrrr r r r rsrc@seZdZdZdZdZdS)CDatazA CDATA block.z N)rrr r!rrr r r r rsrc@seZdZdZdZdZdS)ProcessingInstructionzA SGML processing instruction.zN)rrr r!rrr r r r rsrc@seZdZdZdZdZdS)XMLProcessingInstructionzAn XML processing instruction.zN)rrr r!rrr r r r rsrc@seZdZdZdZdZdS)CommentzAn HTML or XML comment.zN)rrr r!rrr r r r rsrc@seZdZdZdZdZdS) DeclarationzAn XML declaration.zN)rrr r!rrr r r r rsrc@s$eZdZdZeddZdZdZdS)DoctypezA document type declaration.cCsN|pd}|dk r2|d|7}|dk rF|d|7}n|dk rF|d|7}t|S)aGenerate an appropriate document type declaration for a given public ID and system ID. :param name: The name of the document's root element, e.g. 'html'. :param pub_id: The Formal Public Identifier for this document type, e.g. '-//W3C//DTD XHTML 1.1//EN' :param system_id: The system identifier for this document type, e.g. 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' :return: A Doctype. r%Nz PUBLIC "%s"z "%s"z SYSTEM "%s")r)rrZpub_id system_idrr r r for_name_and_idss   zDoctype.for_name_and_idsz N)rrr r! classmethodrrrr r r r rs rc@seZdZdZdS) StylesheetzA NavigableString representing an stylesheet (probably CSS). Used to distinguish embedded stylesheets from textual content. N)rrr r!r r r r r src@seZdZdZdS)ScriptzA NavigableString representing an executable script (probably Javascript). Used to distinguish executable code from textual content. N)rrr r!r r r r rsrc@seZdZdZdS)TemplateStringzA NavigableString representing a string found inside an HTML template embedded in a larger document. Used to distinguish such strings from the main body of the document. N)rrr r!r r r r rsrc@s:eZdZdZdfddZedZddZedd Z e Z ed d Z e j d d Z d e effddZeeZeddZdd e effddZeZeeZddZdgddZddZddZdhddZdidd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Z d-d.Z!d/d0Z"d1d2Z#d3d4Z$d5d6Z%d7d8Z&d9d:Z'djdd?Z)d@dAZ*e+r\e)Z*Z(e,ddBdCfdDdEZ-de,dBfdFdGZ.dHdIZ/dkdJdKZ0de,dBfdLdMZ1de,dBfdNdOZ2e,d dPfdQdRZ3didSdfdTdUZ4e4Z5didSddfdVdWZ6e6Z7e6Z8edXdYZ9edZd[Z:dld\d]Z;dmd^d_ZdddeZ?dS)nrWzRepresents an HTML or XML tag that is part of a parse tree, along with its attributes and contents. When Beautiful Soup parses the markup penguin, it will create a Tag object representing the tag. NcCs|dkrd|_n|j|_|dkr(td||_||_||_|rD|jr`| dk sT| dk r`| |_| |_|dkrni}n4|r|dk r|j r| |j|}qt |}nt |}|r|j |_ n| |_ ||_g|_|||d|_|dkr| |_| |_ ||_n&|||||_|j |_ |j|_dS)aBasic constructor. :param parser: A BeautifulSoup object. :param builder: A TreeBuilder. :param name: The name of the tag. :param namespace: The URI of this Tag's XML namespace, if any. :param prefix: The prefix for this Tag's XML namespace, if any. :param attrs: A dictionary of this Tag's attribute values. :param parent: The PageElement to use as this Tag's parent. :param previous: The PageElement that was parsed immediately before this tag. :param is_xml: If True, this is an XML tag. Otherwise, this is an HTML tag. :param sourceline: The line number where this tag was found in its source document. :param sourcepos: The character position within `sourceline` where this tag was found. :param can_be_empty_element: If True, this tag should be represented as . If False, this tag should be represented as . :param cdata_list_attributes: A list of attributes whose values should be treated as CDATA if they ever show up on this tag. :param preserve_whitespace_tags: A list of tag names whose contents should have their whitespace preserved. Nz%No value provided for new tag's name.F) parser_classrrIrrrZstore_line_numbers sourceline sourceposcdata_list_attributesZ$_replace_cdata_list_attribute_valuesdictrFrGrnr;r<hiddencan_be_empty_elementpreserve_whitespace_tagsZset_up_substitutions)r parserbuilderrrrrnr6rrFrrrrrr r r __init__,sF       z Tag.__init__rcCs|t|d|j|j|j|j|j|j|j|j|j |j |j d }xdD]}t ||t ||q@Wx|jD]}||qbW|S)zA copy of a Tag is a new Tag, unconnected to the parse tree. Its contents are a copy of the old Tag's contents. N)rFrrrrr)rr)rrrrrrnrDrrrrrrrr;rRr)r cloner rPr r r rs    z Tag.__copy__cCst|jdko|jS)a7Is this tag an empty-element tag? (aka a self-closing tag) A tag that has contents is never an empty-element tag. A tag that has no contents may or may not be an empty-element tag. It depends on the builder used to create the tag. If the builder has a designated list of empty-element tags, then only a tag whose name shows up in that list is considered an empty-element tag. If the builder has no designated list of empty-element tags, then any tag with no contents is an empty-element tag. r)r\r;r)r r r r is_empty_elementszTag.is_empty_elementcCs0t|jdkrdS|jd}t|tr*|S|jS)aConvenience property to get the single string within this PageElement. TODO It might make sense to have NavigableString.string return itself. :return: If this element has a single string child, return value is that string. If this element has one child tag, return value is the 'string' attribute of the child tag, recursively. If this element is itself a string, has no children, or has more than one child, return value is None. r-Nr)r\r;r=rYr)r rPr r r rs   z Tag.stringcCs||||dS)z2Replace this PageElement's contents with `string`.N)clearrRr)r rr r r rsFccs\xV|jD]L}|dkrt|tr|dk r4t||kr4q|rN|}t|dkrNq|VqWdS)aYield all strings of certain classes, possibly stripping them. :param strip: If True, all strings will be stripped before being yielded. :types: A tuple of NavigableString subclasses. Any strings of a subclass not found in this list will be ignored. By default, this means only NavigableString and CData objects will be considered. So no comments, processing instructions, etc. :yield: A sequence of strings. Nr) descendantsr=rYrstripr\)r rtypesZ descendantr r r _all_stringss  zTag._all_stringsccsx|dD] }|Vq WdS)zrYield all strings in the document, stripping them first. :yield: A sequence of stripped strings. TN)r)r rr r r stripped_stringsszTag.stripped_stringsr%cCs|dd|j||dDS)aHGet all child strings, concatenated using the given separator. :param separator: Strings will be concatenated using this separator. :param strip: If True, strings will be stripped before being concatenated. :types: A tuple of NavigableString subclasses. Any strings of a subclass not found in this list will be ignored. By default, this means only NavigableString and CData objects will be considered. So no comments, processing instructions, stylesheets, etc. :return: A string. cSsg|]}|qSr r )rcr@r r r sz Tag.get_text..)r)joinr)r separatorrrr r r get_textsz Tag.get_textcCs>||}x,|dk r8|j}|jg|_d|_|}qWdS)aRecursively destroys this PageElement and its children. This element will be removed from the tree and wiped out; so will everything beneath it. The behavior of a decomposed PageElement is undefined and you should never use one for anything, but if you need to _check_ whether an element has been decomposed, you can use the `decomposed` property. NT)rKr8__dict__rr;r)r rnr r r decomposes   z Tag.decomposecCs^|r:xT|jddD] }t|tr,|q|qWn x|jddD] }|qJWdS)zWipe out all children of this PageElement by calling extract() on them. :param decompose: If this is True, decompose() (a more destructive method) will be called instead of extract(). N)r;r=rWrrK)r rrr r r rs  z Tag.clearcCsg}x|t|jD]n\}}t|tr*||t|jdkr>q|j|d}t|trt|trt|tst|ts||qWxFt |D]:}|j|}|j|d}| t||}| |qWdS)zSmooth out this element's children by consolidating consecutive strings. This makes pretty-printed output look more natural following a lot of operations that modified the tree. r-N) enumerater;r=rWsmoothr\rYrrRrOrKrM)r Zmarkedrabrr r r r-s$        z Tag.smoothcCs0x"t|jD]\}}||kr |Sq WtddS)zFind the index of a child by identity, not value. Avoids issues with tag.contents.index(element) getting the index of equal elements. :param element: Look for this PageElement in `self.contents`. zTag.index: element not in tagN)rr;rI)r rrrPr r r rJSsz Tag.indexcCs|j||S)zReturns the value of the 'key' attribute for the tag, or the value given for 'default' if it doesn't have that attribute.)rnget)r keydefaultr r r r`szTag.getcCs |||}t|ts|g}|S)a&The same as get(), but always returns a list. :param key: The attribute to look for. :param default: Use this value if the attribute is not present on this PageElement. :return: A list of values, probably containing only a single value. )rr=rZ)r rrrr r r get_attribute_listfs  zTag.get_attribute_listcCs ||jkS)z|}npt|tsRt|tr^d|}n0t|tsrt|}nt|tr|dk r| |}| |} t|d| | }| |q(Wd} d} d} |j r|j d} |jr|jpd} nd| |jf} ||} d}d}|dk r d|d}| r4|}|d}nd}||||}|jrT|}ng}d}|rpdd|}|dk r| || d| |j|| f| r| d | || r|r|d d kr| d | r| r| || | |dk r| r|jr| d d|}|S) aRender a Unicode representation of this PageElement and its contents. :param indent_level: Each line of the rendering will be indented this many spaces. Used internally in recursive calls while pretty-printing. :param eventual_encoding: The tag is destined to be encoded into this encoding. This method is _not_ responsible for performing that encoding. This information is passed in so that it can be substituted in if the document contains a tag that mentions the document's encoding. :param formatter: A Formatter object, or a string naming one of the standard formatters. N =r%rzr-z <%s%s%s%s> r5)r=rr> attributesrZtuplerrr"r(Zattribute_valueZquoted_attribute_valuerRrrZvoid_element_close_prefixr_should_pretty_printdecode_contentsrr9)r reventual_encodingrArrnrvaldecodedroclosecloseTagr pretty_printspaceZ indent_spaceZindent_contentsr;r@Zattribute_stringr r r rst                          z Tag.decodecCs|dk o|j p|j|jkS)zShould this tag be pretty-printed? Most of them should, but some (such as
 in HTML
        documents) should not.
        N)rr)r	rrrrreszTag._should_pretty_printcCs*|dkr|jd|dS|j|d|dSdS)aPretty-print this PageElement as a string.

        :param encoding: The eventual encoding of the string. If this is None,
            a Unicode string will be returned.
        :param formatter: A Formatter object, or a string naming one of
            the standard formatters.
        :return: A Unicode string (if encoding==None) or a bytestring 
            (otherwise).
        NT)rA)rr()r	r'rArrrprettifyss
zTag.prettifyc	Cst|ts||}|dk	}g}x|D]}d}t|trD||}nt|trb||||||jor|j	|jk}|r|r|s|
}|r&|r|s|d|d|||r&|s&|dq&Wd|S)aRenders the contents of this tag as a Unicode string.

        :param indent_level: Each line of the rendering will be
           indented this many spaces. Used internally in
           recursive calls while pretty-printing.

        :param eventual_encoding: The tag is destined to be
           encoded into this encoding. decode_contents() is _not_
           responsible for performing that encoding. This information
           is passed in so that it can be substituted in if the
           document contains a  tag that mentions the document's
           encoding.

        :param formatter: A Formatter object, or a string naming one of
            the standard Formatters.
        Nrr-rr%)r=rr>rYrrWrRrrrrr)	r	rrrArr@rEroZpreserve_whitespacerrrrs*





zTag.decode_contentscCs||||}||S)aRenders the contents of this PageElement as a bytestring.

        :param indent_level: Each line of the rendering will be
           indented this many spaces. Used internally in
           recursive calls while pretty-printing.

        :param eventual_encoding: The bytestring will be in this encoding.

        :param formatter: A Formatter object, or a string naming one of
            the standard Formatters.

        :return: A bytestring.
        )rr()r	rr'rAr;rrrencode_contentsszTag.encode_contentsrcCs|sd}|j||dS)z(Deprecated method for BS3 compatibility.N)rr')r	)r	r'ZprettyPrintZindentLevelrrrrenderContentsszTag.renderContentsTcKs*d}|j||||df|}|r&|d}|S)aLook in the children of this PageElement and find the first
        PageElement that matches the given criteria.

        All find_* methods take a common set of arguments. See the online
        documentation for detailed explanations.

        :param name: A filter on tag name.
        :param attrs: A dictionary of filters on attribute values.
        :param recursive: If this is True, find() will perform a
            recursive search of this PageElement's children. Otherwise,
            only the direct children will be considered.
        :param limit: Stop looking after finding this many results.
        :kwargs: A dictionary of filters on attribute values.
        :return: A PageElement.
        :rtype: bs4.element.Tag | bs4.element.NavigableString
        Nr-r)r)r	rrn	recursiverorprrrrrrs
zTag.findcKs&|j}|s|j}|j|||||f|S)aLook in the children of this PageElement and find all
        PageElements that match the given criteria.

        All find_* methods take a common set of arguments. See the online
        documentation for detailed explanations.

        :param name: A filter on tag name.
        :param attrs: A dictionary of filters on attribute values.
        :param recursive: If this is True, find_all() will perform a
            recursive search of this PageElement's children. Otherwise,
            only the direct children will be considered.
        :param limit: Stop looking after finding this many results.
        :kwargs: A dictionary of filters on attribute values.
        :return: A ResultSet of PageElements.
        :rtype: bs4.element.ResultSet
        )rchildrenrr)r	rrnrrortrprrrrrszTag.find_allcCs
t|jS)zkIterate over all direct children of this PageElement.

        :yield: A sequence of PageElements.
        )rr;)r	rrrrszTag.childrenccs@t|jsdS|j}|jd}x||k	r:|V|j}q$WdS)zIterate over all children of this PageElement in a
        breadth-first sequence.

        :yield: A sequence of PageElements.
        Nr)r\r;rUr8)r	ZstopNodecurrentrrrr
s



zTag.descendantscKs"|j||df|}|r|dSdS)aPerform a CSS selection operation on the current element.

        :param selector: A CSS selector.

        :param namespaces: A dictionary mapping namespace prefixes
           used in the CSS selector to namespace URIs. By default,
           Beautiful Soup will use the prefixes it encountered while
           parsing the document.

        :param kwargs: Keyword arguments to be passed into SoupSieve's 
           soupsieve.select() method.

        :return: A Tag.
        :rtype: bs4.element.Tag
        r-rN)select)r	selector
namespacesrprrrr
select_oneszTag.select_onecKsH|dkr|j}|dkrd}tdkr*tdtj||||f|}td|S)aPerform a CSS selection operation on the current element.

        This uses the SoupSieve library.

        :param selector: A string containing a CSS selector.

        :param namespaces: A dictionary mapping namespace prefixes
           used in the CSS selector to namespace URIs. By default,
           Beautiful Soup will use the prefixes it encountered while
           parsing the document.

        :param limit: After finding this number of results, stop looking.

        :param kwargs: Keyword arguments to be passed into SoupSieve's 
           soupsieve.select() method.

        :return: A ResultSet of Tags.
        :rtype: bs4.element.ResultSet
        NrzLCannot execute CSS selectors because the soupsieve package is not installed.)_namespaces	soupsieveNotImplementedErrorrr)r	rrrtrprrrrr/sz
Tag.selectcCs|jS)zDeprecated generator.)r)r	rrrchildGeneratorTszTag.childGeneratorcCs|jS)zDeprecated generator.)r)r	rrrrecursiveChildGeneratorXszTag.recursiveChildGeneratorcCstd|||S)zDeprecated method. This was kind of misleading because has_key()
        (attributes) was different from __in__ (contents).

        has_key() is gone in Python 3, anyway.
        z2has_key is deprecated. Use has_attr("%s") instead.)rrr)r	rrrrhas_key\szTag.has_key)NNNNNNNNNNNNNN)F)N)N)r)Nr)N)NN)@rrr r!rrZparserClassrrrZ
isSelfClosingrrrYrrstringsrrZgetTextrorrrrJrrrrrrrrrrrrrrrrrrrrr(rrrrr	r
rZ	findChildrZfindAllZfindChildrenrrrrrrrrrrrrW$s
\	
&


c
-		

%rWc@sTeZdZdZdidfddZddZddZdifd	d
ZeZddZ	dd
dZ
dS)ra&Encapsulates a number of ways of matching a markup element (tag or
    string).

    This is primarily used to underpin the find_* methods, but you can
    create one yourself and pass it in as `parse_only` to the
    `BeautifulSoup` constructor, to parse a subset of a large
    document.
    NcKs|||_t|ts"||d<d}d|kr<|d|d<|d=|r\|rX|}||n|}i}x&t|D]\}}||||<qnW||_|||_	dS)aConstructor.

        The SoupStrainer constructor takes the same arguments passed
        into the find_* methods. See the online documentation for
        detailed explanations.

        :param name: A filter on tag name.
        :param attrs: A dictionary of filters on attribute values.
        :param text: A filter for a NavigableString with specific text.
        :kwargs: A dictionary of filters on attribute values.
        classNclass_)
_normalize_search_valuerr=rcopyupdaterZitemsrnro)r	rrnrorpZnormalized_attrsrrrrrrqs"
zSoupStrainer.__init__cCst|ts0t|ts0t|ds0t|ts0|dkr4|St|trH|dSt|drg}xF|D]>}t|drt|tst|ts||q\|||q\W|Stt|S)Nr,utf8r)	r=rrr]boolbytesrrRr)r	rZ	new_valuevrrrrs




z$SoupStrainer._normalize_search_valuecCs |jr|jSd|j|jfSdS)z5A human-readable representation of this SoupStrainer.z%s|%sN)rorrn)r	rrrrszSoupStrainer.__str__c
CsLd}d}t|tr|}|}t|jtr@|r@|js@|j|jkr@dSt|jtoVt|t}|jr|s|rt|||js|s$|||jr$|r|||}nrd}d}xht|j	D]V\}}	|st
|dr|}ni}x|D]\}
}|||
<qW||}|||	sd}PqW|r$|r |}n|}|rH|jrH||j
|jsHd}|S)aCheck whether a Tag with the given name and attributes would
        match this SoupStrainer.

        Used prospectively to decide whether to even bother creating a Tag
        object.

        :param markup_name: A tag name as found in some markup.
        :param markup_attrs: A dictionary of attributes as found in some markup.

        :return: True if the prospective tag would match this SoupStrainer;
            False otherwise.
        NFTr)r=rWrrrr_matchesrZrnrr]rror)
r	Zmarkup_nameZmarkup_attrsrmarkupZcall_function_with_tag_datar,Zmarkup_attr_mapr

match_againstkr"
attr_valuerrr
search_tagsH



 zSoupStrainer.search_tagcCsd}t|drFt|ttfsFx|D]}t|tr"||r"|}Pq"Wnjt|trn|jrb|jsb|jr|	|}nBt|tst|tr|js|js|
||jr|}ntd|j|S)zFind all items in `markup` that match this SoupStrainer.

        Used by the core _find_all() method, which is ultimately
        called by all find_* methods.

        :param markup: A PageElement or a list of them.
        Nrz&I don't know how to match against a %s)
r]r=rWrrYr+rorrnr(r#	Exceptionr)r	r$rrrrrr+s"	





zSoupStrainer.searchc	Cs~d}t|tst|trPx|D]}|||rdSqW|d||rLdSdS|dkr`|dk	St|trr||S|}t|tr|j}||}|dkr|St	|drt|t
s|st}xL|D]@}|jr|}nt
|}||krqq||||||rdSqWdSd}|s,t|t
r,||k}|sHt	|drH||S|szt|trz|jrz||jd|j|S|S)NFTrrr+r)r=rZrr#rrrWrrr]rsetridaddr+r)	r	r$r%Z
already_triedritemZoriginal_markuprr,rrrr#sV






zSoupStrainer._matches)N)rrr r!rrrr(Z	searchTagr+r#rrrrrgs&=!rcs*eZdZdZdfdd	ZddZZS)rzTA ResultSet is just a list that keeps track of the SoupStrainer
    that created it.rcstt||||_dS)zlConstructor.

        :param source: A SoupStrainer.
        :param result: A list of PageElements.
        N)superrrsource)r	r/r)rrrrrszResultSet.__init__cCstd|dS)z7Raise a helpful exception to explain a common code fix.zResultSet object has no attribute '%s'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?N)r)r	rrrrr{szResultSet.__getattr__)r)rrr r!rr
__classcell__rr)rrros	r).__license__collections.abcrImportErrorecollectionsr1sysrrrZ
bs4.formatterrrrrversion_inforr2Znonwhitespace_reZ
whitespace_rerr*r&rrr"r#r)objectr4rYrrrrrrrrrrrWrrZrrrrrs

YJ			I