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

Time:12-06

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?

CodePudding user response:

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()

CodePudding user response:

To turn this JavaScript

  • Related