在这种情况下,A
是给定类型的单个结果。
>>> type(A)
<class 'bs4.element.Tag'>
当您遍历此对象A
时,您将产生一个对象 B:
>>> type(B)
<class 'bs4.element.NavigableString'>
在这种情况下,bs4.element.NavigableString
实际上并不包含方法renderContents
。可以这样验证:
>>> dir(B)
['HTML_FORMATTERS', 'PREFIX', 'SUFFIX', 'XML_FORMATTERS', '__add__', '__class__', '__contains__', '__copy__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_attr_value_as_string', '_attribute_checker', '_find_all', '_find_one', '_formatter_field_name_split', '_formatter_for_name', '_formatter_parser', '_is_xml', '_lastRecursiveChild', '_last_descendant', '_tag_name_matches_and', 'append', 'attribselect_re', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'extract', 'fetchNextSiblings', 'fetchParents', 'fetchPrevious', 'fetchPreviousSiblings', 'find', 'findAllNext', 'findAllPrevious', 'findNext', 'findNextSibling', 'findNextSiblings', 'findParent', 'findParents', 'findPrevious', 'findPreviousSibling', 'findPreviousSiblings', 'find_all_next', 'find_all_previous', 'find_next', 'find_next_sibling', 'find_next_siblings', 'find_parent', 'find_parents', 'find_previous', 'find_previous_sibling', 'find_previous_siblings', 'format', 'format_string', 'index', 'insert', 'insert_after', 'insert_before', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'islower', 'isnumeric', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'name', 'next', 'nextGenerator', 'nextSibling', 'nextSiblingGenerator', 'next_element', 'next_elements', 'next_sibling', 'next_siblings', 'output_ready', 'parent', 'parentGenerator', 'parents', 'partition', 'previous', 'previousGenerator', 'previousSibling', 'previousSiblingGenerator', 'previous_element', 'previous_elements', 'previous_sibling', 'previous_siblings', 'replace', 'replaceWith', 'replaceWithChildren', 'replace_with', 'replace_with_children', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'setup', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'tag_name_re', 'title', 'translate', 'unwrap', 'upper', 'wrap', 'zfill']
这可能是您真正想要的(在 findAll 上没有切片符号):
A = soup.findAll('strong',{'class':'name fn'}) # Notice there is no [0] slice notation here.
for B in A:
print B.renderContents()