Python使用Selenium如何获取指定元素的所有子元素?
Python Selenium 实现获取body标签下所有子元素名称方案
原有代码错误说明
- Selenium 的 WebElement 对象没有
childrens属性,获取指定父元素的直接子元素需要使用find_elements(By.XPATH, './*')方法,其中./表示基于当前父元素查找,*匹配所有直接子节点 - Python Selenium 中获取元素标签名的属性为
.tag_name,并非JS中的tagName - 你定义的无头模式配置没有传入webdriver的初始化参数,配置不生效
- Selenium 4.0及以上版本已弃用
executable_path参数,推荐使用Service类指定geckodriver路径
正确可运行代码
Selenium 4.x 版本写法
from selenium import webdriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.firefox.service import Service from selenium.webdriver.common.by import By # 配置火狐浏览器参数 option = Options() option.headless = True # 指定geckodriver路径 service = Service(executable_path=r'C:\geck\geckodriver.exe') # 初始化driver,传入配置 driver = webdriver.Firefox(service=service, options=option) driver.get('https://www.google.com.br/') # 定位body元素 body = driver.find_element(By.TAG_NAME, 'body') # 获取body下所有直接子元素 children = body.find_elements(By.XPATH, './*') # 遍历输出标签名 for child in children: print(child.tag_name) driver.quit()
Selenium 3.x 兼容写法
from selenium import webdriver from selenium.webdriver.firefox.options import Options option = Options() option.headless = True driver = webdriver.Firefox(executable_path=r'C:\geck\geckodriver.exe', options=option) driver.get('https://www.google.com.br/') body = driver.find_element_by_tag_name('body') children = body.find_elements_by_xpath('./*') for child in children: print(child.tag_name) driver.quit()
依赖安装命令
pip install pandas pip install bs4 pip install selenium pip install requests
内容的提问来源于stack exchange,提问作者sysOut
相关产品推荐
相关产品推荐

