Mathematics
Mathematics

Reputation: 7628

How to specify childrens in anytree and print a tree

I am trying to print a tree using Wikipedia's sections but I am not able to figure out how to specify children node in anytree. Here is what I have tried so far,

import wikipediaapi
from anytree import Node, RenderTree, DoubleStyle
wiki_wiki = wikipediaapi.Wikipedia('en')
main_page = wiki_wiki.page('Stack_Overflow')
sections =  main_page.sections
print(RenderTree(sections))

but I am getting this error,

Traceback (most recent call last):
  File "so.py", line 6, in <module>
    print(RenderTree(sections))
  File "/usr/lib/python3.4/site-packages/anytree/render.py", line 292, in __str__
    lines = ["%s%r" % (pre, node) for pre, _, node in self]
  File "/usr/lib/python3.4/site-packages/anytree/render.py", line 292, in <listcomp>
    lines = ["%s%r" % (pre, node) for pre, _, node in self]
  File "/usr/lib/python3.4/site-packages/anytree/render.py", line 272, in __next
    children = node.children
AttributeError: 'list' object has no attribute 'children'

I am expecting this output

1   History
1.1 Content criteria
1.2 User suspension
2   Statistics
3   Technology
4   Reception
5   See also
6   References
7   External links

I want it to go as deep as possible

Upvotes: 0

Views: 672

Answers (1)

Prune
Prune

Reputation: 77847

I think you need to double-check the docs and work through an example or two in the anytree class. This class works with its self-defined tree structure, but sections is a straightforward list, not suitable to present to RenderTree. I checked your interfacing with some simple print commands:

sections =  main_page.sections
print(type(sections), len(sections))
print("\n------------ sections -----------\n", sections)
render = RenderTree(sections)
print(type(render))
print("\n------------ final print -----------\n")
print(render)
print("\n------------ final print done -----------\n")

Output:

<class 'list'> 7

------------ sections -----------
 [Section: History (1):
The website was created
...
]
<class 'anytree.render.RenderTree'>

------------ final print -----------

Traceback (most recent call last):
...

Your list input does not have the Node structure that anytree expects.

Upvotes: 1

Related Questions