0

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

Prune
  • 76,765
  • 14
  • 60
  • 81
Mathematics
  • 7,314
  • 25
  • 77
  • 152

1 Answers1

1

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.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • thank you so much for your input, in that case anytree isn't a must for me, any other library would work I guess, but I am not sure which one, if you know how to print structure like required by me please share, I will keep looking at meantime – Mathematics Mar 13 '19 at 06:32
  • References to off-site resources is generally out of scope for Stack Overflow -- but I don't mind that you asked in the normal flow of the question. *I* would handle this by writing my own parsing and extraction code, looking for the `Section:` header, the `level` that follows, and the very helpful `Subsections(n):` counter (`n` is the number of subsections at that level, which immediately follow). – Prune Mar 13 '19 at 18:10