__dict __。items()不返回所有对象属性

时间:2013-06-13 09:19:56

标签: python oop attributes beautifulsoup

考虑:

>>> result = requests.get('http://dotancohen.com')
>>> soup = BeautifulSoup(result.text)
>>> a = soup.find('a')
>>> for k,v in a.__dict__.items():
...     print(str(k)+": "+str(v))
... 
can_be_empty_element: False
previous_element: <h1><a class="title" href="/">Dotan Cohen</a></h1>
next_sibling: None
name: a
parent: <h1><a class="title" href="/">Dotan Cohen</a></h1>
namespace: None
prefix: None
previous_sibling: None
attrs: {'href': '/', 'class': ['title']}
next_element: Dotan Cohen
parser_class: <class 'bs4.BeautifulSoup'>
hidden: False
contents: ['Dotan Cohen']
>>> pprint(a)
<a class="title" href="/">Dotan Cohen</a>
>>>

pprint返回的值不是__dict__.items()返回的任何属性的值。这对我来说意味着a中存在__dict__.items()未归属的属性。我如何访问这些属性?

1 个答案:

答案 0 :(得分:2)

实例字典中没有遗漏任何属性。我们来看看元素的表示:

<a class="title" href="/">Dotan Cohen</a>

我们有一个标记名称(a),属性(titlehref,带有值),我们有文字内容(Dotan Cohen)。这些 all 出现在您列出的实例属性中:

  • name: a
  • attrs: {'href': '/', 'class': ['title']}
  • contents: ['Dotan Cohen']

contents是此元素的直接后代列表;只有一个文本对象(NavigableString个实例使用的表示形式就像常规字符串一样)。

您可以使用vars() built-in API function列出实例属性。我发现你已经在使用pprint();而不是循环.items(),只需使用pprint(vars(a))并保存自己输入一个完整的循环;作为奖励pprint()首先对键进行排序:

>>> pprint(vars(a))
{'attrs': {'class': ['title'], 'href': '/'},
 'can_be_empty_element': False,
 'contents': [u'Dotan Cohen'],
 'hidden': False,
 'name': 'a',
 'namespace': None,
 'next_element': u'Dotan Cohen',
 'next_sibling': None,
 'parent': <h1><a class="title" href="/">Dotan Cohen</a></h1>,
 'parser_class': <class 'bs4.BeautifulSoup'>,
 'prefix': None,
 'previous_element': <h1><a class="title" href="/">Dotan Cohen</a></h1>,
 'previous_sibling': None}

您正在查看的字符串由元素类的.__repr__()挂钩构建:

>>> a.__repr__()
'<a class="title" href="/">Dotan Cohen</a>'

通常在对象上使用repr()时调用:

>>> repr(a)
'<a class="title" href="/">Dotan Cohen</a>'

该字符串是根据您在对象属性中看到的已解析元素信息构建的。

相关问题