首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用selenium获取python中元素的所有子元素?

如何使用selenium获取python中元素的所有子元素?
EN

Stack Overflow用户
提问于 2021-12-05 15:14:56
回答 2查看 2K关注 0票数 0

我如何将这个JavaScript转换成Python来从父元素中获取所有子元素?

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

代码语言:javascript
运行
复制
e = document.getElementsByTagName('body')[0].children

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

在蟒蛇里我试着这么做,但我做不到

代码语言:javascript
运行
复制
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()

用于安装软件包的命令:

代码语言:javascript
运行
复制
pip install pandas
pip install bs4
pip install selenium
pip install requests

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-12-05 16:10:05

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

代码语言:javascript
运行
复制
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()
票数 1
EN

Stack Overflow用户

发布于 2021-12-05 15:53:28

将此转换为Python,以获取父元素中的所有子元素

代码语言:javascript
运行
复制
e = document.getElementsByTagName('body')[0].children

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

以一种简单而又简洁的方式,您只需要在JavaScript中传递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)
}
""")

控制台快照:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70235673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档