python、selenium中切换帧的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28723143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
function for switching frames in python, selenium
提问by Andigger
I'm looking for a function that makes it easier to switch between two frames. Right now, every time I need to switch between frames, I'm doing this by the following code:
我正在寻找一种可以更轻松地在两帧之间切换的功能。现在,每次我需要在帧之间切换时,我都会通过以下代码执行此操作:
driver.switch_to.frame(driver.find_element_by_css_selector("frame[name='nav']"))
driver.switch_to.frame(driver.find_element_by_css_selector("frame[name='content']"))
My goal is to get a function that takes an argument just to change nav or content since the rest is basically the same.
我的目标是获得一个函数,它只需要一个参数来改变导航或内容,因为其余的基本相同。
What I've already tried is:
我已经尝试过的是:
def frame_switch(content_or_nav):
x = str(frame[name=str(content_or_nav)] #"frame[name='content_or_nav']"
driver.switch_to.frame(driver.find_element_by_css_selector(x))
But it gives me an error
但它给了我一个错误
x = str(frame[name=str(content_or_nav)]
^
SyntaxError: invalid syntax
语法错误:无效语法
采纳答案by ddavison
The way this is written, it's trying to parse CSS code as Python code. You don't want that.
它的编写方式是尝试将 CSS 代码解析为 Python 代码。你不想那样。
This function is suitable:
此功能适用于:
def frame_switch(css_selector):
driver.switch_to.frame(driver.find_element_by_css_selector(css_selector))
If you are just trying to switch to the frame based on the name
attribute, then you can use this:
如果你只是想根据name
属性切换到框架,那么你可以使用这个:
def frame_switch(name):
driver.switch_to.frame(driver.find_element_by_name(name))
To switch back to the main window, you can use
要切换回主窗口,您可以使用
driver.switch_to.default_content()