【问题标题】:How to get all children of an element in python using selenium?如何使用 selenium 在 python 中获取元素的所有子元素?
【发布时间】:2022-01-11 01:59:00
【问题描述】:

如何将此 JavaScript 转换为 Python 以从父级获取所有子元素?

此脚本通过控制台从 google.com 站点获取所有元素

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

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

在python中我尝试过这样做,但我做不到

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

用于安装包的命令:

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

如何从 python 中的 body 标签中获取元素名称?

【问题讨论】:

  • 如果你想用 selenium 在 python 中执行 java 脚本,你可以使用这个:driver.execute_script("return document.getElementsByTagName('body')[0].children")
  • 它是driver.find_elements_by_tag_name 复数
  • @QualityMatters 有趣,我可以显示标签名称吗?使用 execute_script?

标签: javascript python selenium


【解决方案1】:

您可以使用body.find_elements_by_xpath("./child::*") 将body 中的所有子元素作为WebElement 对象获取,然后通过访问tag_name 属性获取它们的标签名称

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

【讨论】:

    【解决方案2】:

    将这个JavaScript 变成Python 以从父级获取所有子元素

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

    以一种简单明了的方式,您只需在execute_script() 中传递 JavaScript,如下所示:

    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)
    }
    """)
    

    控制台快照:

    【讨论】:

    • 谢谢你,对我帮助很大!
    • 通过 console 从 google.com 站点获取所有元素:根据您的问题,我认为您想要控制台上的输出 :)
    • @megaultron 很高兴能够帮助您! Upvote 如果此/任何答案对您/对您有帮助,则为未来读者的利益提供答案。
    猜你喜欢
    • 2021-12-25
    • 2012-05-11
    • 2017-08-22
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多