我如何将这个JavaScript转换成Python来从父元素中获取所有子元素?
此脚本通过控制台从google.com站点获取所有元素。
e = document.getElementsByTagName('body')[0].children
for (let i = 0; i < e.length;i++){
console.log(e[i].tagName)
}
在蟒蛇里我试着这么做,但我做不到
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标记中获取元素名称?
发布于 2021-12-05 16:10:05
您可以使用body.find_elements_by_xpath("./child::*")
获取主体中的所有子元素作为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()
发布于 2021-12-05 15:53:28
将此转换为Python,以获取父元素中的所有子元素
e = document.getElementsByTagName('body')[0].children
for (let i = 0; i < e.length;i++){
console.log(e[i].tagName)
}
以一种简单而又简洁的方式,您只需要在JavaScript中传递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)
}
""")
控制台快照:
https://stackoverflow.com/questions/70235673
复制相似问题