鱼C论坛

 找回密码
 立即注册
查看: 1752|回复: 3

[已解决]selenium如何获取当前iframe的ID或name?

[复制链接]
发表于 2023-6-1 22:10:14 | 显示全部楼层 |阅读模式
50鱼币
selenium有时需切入iframe才能定位到元素,在切换iframe框架前,我想先获取当前iframe的ID或name?请问有什么方法?谢谢
最佳答案
2023-6-1 22:10:15
难道你是这个意思?
css selector:
from selenium import webdriver
import time as t, bs4 as b
driver = webdriver.Chrome()
driver.get("https://www.114514.com")
t.sleep(1)
soup = b.BeautifulSoup(driver.page_source, 'lxml')
tag = soup.select_one("css选择器")
print(tag['id'],tag['name'])
xpath:
from selenium import webdriver
import time as t
from lxml import html
driver = webdriver.Chrome()
driver.get("https://www.114514.com")
t.sleep(1)
tree = html.fromstring(driver.page_source)
tag = tree.xpath("你的xpath")
tag = html.tostring(tag,encoding='unicode')
print(tag)
pip install bs4 lxml

最佳答案

查看完整内容

难道你是这个意思? css selector: xpath: pip install bs4 lxml

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-6-1 22:10:15 | 显示全部楼层    本楼为最佳答案   
难道你是这个意思?
css selector:
from selenium import webdriver
import time as t, bs4 as b
driver = webdriver.Chrome()
driver.get("https://www.114514.com")
t.sleep(1)
soup = b.BeautifulSoup(driver.page_source, 'lxml')
tag = soup.select_one("css选择器")
print(tag['id'],tag['name'])
xpath:
from selenium import webdriver
import time as t
from lxml import html
driver = webdriver.Chrome()
driver.get("https://www.114514.com")
t.sleep(1)
tree = html.fromstring(driver.page_source)
tag = tree.xpath("你的xpath")
tag = html.tostring(tag,encoding='unicode')
print(tag)
pip install bs4 lxml
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-6-1 22:10:57 | 显示全部楼层
本帖最后由 歌者文明清理员 于 2023-6-1 22:14 编辑

f12查看

Snipaste_2023-06-01_22-14-08.png
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-6-1 22:12:39 | 显示全部楼层
对不起,但是目前的Selenium API并未提供一个直接的方法来获取当前iframe的id或name。你在一个特定的iframe中工作时,Selenium不存储该iframe的引用或任何关于它的信息。当你切换到一个iframe时,你只是告诉Selenium在那个特定的上下文中执行后续的命令。

如果你需要在不同的iframes之间切换,你可能需要在切换到一个新的iframe之前,自己保存你之前所在的iframe的id或name。

在Selenium中,你可以使用 switch_to.default_content() 来切回主文档。如果你需要切换回之前的iframe,你需要再次调用 switch_to.frame() 并使用你保存的id或name。

这里有一个例子展示了如何在iframes之间切换:
# 假设你开始在主文档中

# 切换到一个iframe
driver.switch_to.frame('some-frame-id')

# 执行一些操作

# 切换回主文档
driver.switch_to.default_content()

# 现在你可以切换到另一个iframe,或者切回你之前的iframe
driver.switch_to.frame('some-other-frame-id')

# 或者
driver.switch_to.frame('some-frame-id')

希望这对你有所帮助!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-22 23:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表