selenium切换frame(iframe)

例如网页代码为:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<iframe id= "baidu" name="百度" src="http://www.BAIDU.com" HEIGHT="300" WIDTH="1280"></iframe>
<iframe id= "sougou" name="搜狗" src="https://www.sogou.com/" HEIGHT="300" WIDTH="1280"></iframe>
</body>
</html>


页面如下:

 



当我们需要去定位百度搜索框的ID时,如上面的源码所示,是没有百度搜索框的ID,因为百度和搜狗页面是嵌套的链接,我们需要切换到百度的域里面,才可以定位到搜索框的ID

 

from selenium import webdriver
driver = webdriver.Firefox()
driver.switch_to.frame(0) # 1.用frame的index来定位,第一个是0
# driver.switch_to.frame("baidu") # 2.用id来定位
# driver.switch_to.frame("百度") # 3.用name来定位
# driver.switch_to.frame(driver.find_element_by_tag_name("百度")) # 4.用WebElement对象来定位
# driver.switch_to.frame(driver.find_element_by_xpath("//iframe[contains(@id,'baidu')]")) # 5.用xpath定位,传入WebElement对象


driver.switch_to.frame('baidu) # iframe一层一层的切入
driver.switch_to.parent_frame() # iframe退后操作,一层一层的退回
driver.switch_to.default_content() # 切换到主页面

注意:

使用driver.switch_to_frame()时,会提示该方法已经过时;

需要使用新的driver.switch_to.frame()方法。

 

posted @ 2019-02-15 09:56  樊熙芈  阅读(2597)  评论(3编辑  收藏  举报