sysOut
sysOut

Reputation: 419

How to get all children of an element in python using selenium?

How can I turn this JavaScript into Python to get all child elements from the parent?

This script gets all the elements from the google.com site via console

e = document.getElementsByTagName('body')[0].children

for (let i = 0; i < e.length;i++){
    console.log(e[i].tagName)
}

In python I tried to do this, but I can't

import time
import requests
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.firefox import options
from selenium.webdriver.firefox.options import Options

option = Options()
option.headless = True
driver = webdriver.Firefox(executable_path=r'C:\geck\geckodriver.exe')

driver.get('https://www.google.com.br/')
body = driver.find_element_by_tag_name('body')
childrens = body.childrens

for i in childrens:
    print(i.tagName)

driver.quit()

Commands used to install packages:

pip install pandas
pip install bs4
pip install selenium
pip install requests

How can I get the element names from a body tag in python?

Upvotes: 0

Views: 6530

Answers (2)

vht981230
vht981230

Reputation: 4480

You can use body.find_elements_by_xpath("./child::*") to get all the child elements in body as WebElement object and then get their tag name by accessing the tag_name attribute

import time
import requests
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.firefox import options
from selenium.webdriver.firefox.options import Options

option = Options()
option.headless = True
driver = webdriver.Firefox(executable_path=r'C:\geck\geckodriver.exe')

driver.get('https://www.google.com.br/')
body = driver.find_element_by_tag_name('body')
childrens = body.find_elements_by_xpath("./child::*")

for i in childrens:
    print(i.tag_name)

driver.quit()

Upvotes: 1

undetected Selenium
undetected Selenium

Reputation: 193058

To turn this JavaScript into Python to get all child elements from the parent

e = document.getElementsByTagName('body')[0].children

for (let i = 0; i < e.length;i++){
    console.log(e[i].tagName)
}

in a simple and crispy way you just need to pass the JavaScript within execute_script() as follows:

driver.get("https://www.google.com.br/")
driver.execute_script("""
    e = document.getElementsByTagName('body')[0].children
    for (let i = 0; i < e.length;i++){
    console.log(e[i].tagName)
}
""")

Snapshot of the Console:

JavaScript

Upvotes: -1

Related Questions