when I want to access the children of parsed tree using .contents I am unable to reach the childrens but with find i can find children why?

Viewed 25

using .contents

    `url="https://www.imdb.com/chart/top/"
     import requests
     from bs4 import BeautifulSoup
     re=requests.get(url)
     doc=BeautifulSoup(re.content,"html.parser")
     table=doc.find('tbody',class_="lister-list")
     print(table.contents[0])` 

using find

    `url="https://www.imdb.com/chart/top/"
     import requests
     from bs4 import BeautifulSoup
     re=requests.get(url)
     doc=BeautifulSoup(re.content,"html.parser")
     table=doc.find('tbody',class_="lister-list")
     print(table.find('tr'))`

the .contents is not working why

1 Answers

Because .contents will give you all content of the node - that means string, tags, html comments etc.

If you do print(table.contents) it will print:

['\n', <tr>
<td class="posterColumn">
<span data-value="1" name="rk"></span>
<span data-value="9.23450250788211" name="ir"></span>

...

so first item is string \n (and this will be printed with your script). If you will do print(table.contents[1]) it will give you the <tr> tag.

Related