添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

如何用Selenium在Python中获取一个元素的所有子代?

0 人关注

我怎样才能把这个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标签中获取元素名称?

3 个评论
如果你想用selenium在python中执行java脚本,你可以用这个方法: driver.execute_script("return document.getElementsByTagName('body')[0].children" )
it's driver.find_elements_by_tag_name plural
@QualityMatters 有趣的是,我可以显示标签名称吗?使用execute_script?
javascript
python
selenium
megaultron
megaultron
发布于 2021-12-05
2 个回答
tax evader
tax evader
发布于 2021-12-05
已采纳
0 人赞同

你可以使用 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()
    
undetected Selenium
undetected Selenium
发布于 2021-12-05
0 人赞同

To turn this 脚本 into Python 从父元素中获取所有子元素

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

以一种简单而脆的方式,你只需要通过脚本execute_script()内,如下。

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)