首先看一下html源码
<!DOCTYPE HTML>
<html lang="ch-zn">
<head>
<title>myframe test!!!</title>
<meta charset="utf-8">
<style type="text/css">
h3{text-align:center;color:blue;}
div{text-align:center;}
</style>
</head>
<body>
<h3>myframe</h3>
<div>
<iframe src="http://www.baidu.com/" width="1200px" height="800px" name="myframe" id="if"></iframe>
</div>
</body>
</html>
在html中存在多表单的时候,我们需要切换到表单内部去定位,这里用到的方法是
switch_to.frame
也可以登录126邮箱,看一下它的登录窗口,也是一个
iframe
from selenium import webdriver
from time import sleep
from selenium.common.exceptions import NoSuchElementException
import os
driver = webdriver.Firefox()
file_path = 'file:///' + os.path.abspath('frame.html')
driver.get(file_path)
# 切换到iframe里面,iframe(name='myframe')
driver.switch_to.frame("myframe")
# 下面就是正常操作
# 隐式等待10s
driver.implicitly_wait(10)
try:
el = driver.find_element_by_xpath("//*[@id='kw']")
el1 = driver.find_element_by_id("su")
sleep(2)
except NoSuchElementException as e:
print(e)
else:
el.send_keys("python")
el1.click()
finally:
driver.quit()