Encapsulates a number of ways of matching a markup element (tag or text).
| 887 | |
| 888 | # Next, a couple classes to represent queries and their results. |
| 889 | class SoupStrainer: |
| 890 | """Encapsulates a number of ways of matching a markup element (tag or |
| 891 | text).""" |
| 892 | |
| 893 | def __init__(self, name=None, attrs={}, text=None, **kwargs): |
| 894 | self.name = name |
| 895 | if isinstance(attrs, basestring): |
| 896 | kwargs['class'] = _match_css_class(attrs) |
| 897 | attrs = None |
| 898 | if kwargs: |
| 899 | if attrs: |
| 900 | attrs = attrs.copy() |
| 901 | attrs.update(kwargs) |
| 902 | else: |
| 903 | attrs = kwargs |
| 904 | self.attrs = attrs |
| 905 | self.text = text |
| 906 | |
| 907 | def __str__(self): |
| 908 | if self.text: |
| 909 | return self.text |
| 910 | else: |
| 911 | return "%s|%s" % (self.name, self.attrs) |
| 912 | |
| 913 | def searchTag(self, markupName=None, markupAttrs={}): |
| 914 | found = None |
| 915 | markup = None |
| 916 | if isinstance(markupName, Tag): |
| 917 | markup = markupName |
| 918 | markupAttrs = markup |
| 919 | callFunctionWithTagData = callable(self.name) \ |
| 920 | and not isinstance(markupName, Tag) |
| 921 | |
| 922 | if (not self.name) \ |
| 923 | or callFunctionWithTagData \ |
| 924 | or (markup and self._matches(markup, self.name)) \ |
| 925 | or (not markup and self._matches(markupName, self.name)): |
| 926 | if callFunctionWithTagData: |
| 927 | match = self.name(markupName, markupAttrs) |
| 928 | else: |
| 929 | match = True |
| 930 | markupAttrMap = None |
| 931 | for attr, matchAgainst in self.attrs.items(): |
| 932 | if not markupAttrMap: |
| 933 | if hasattr(markupAttrs, 'get'): |
| 934 | markupAttrMap = markupAttrs |
| 935 | else: |
| 936 | markupAttrMap = {} |
| 937 | for k,v in markupAttrs: |
| 938 | markupAttrMap[k] = v |
| 939 | attrValue = markupAttrMap.get(attr) |
| 940 | if not self._matches(attrValue, matchAgainst): |
| 941 | match = False |
| 942 | break |
| 943 | if match: |
| 944 | if markup: |
| 945 | found = markup |
| 946 | else: |
no outgoing calls
searching dependent graphs…