【发布时间】: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