selenium处理iframe
先看一下这个例子
我们要处理右边的待滑动滑块,首先要先定位到滑块身上。通过查看源码发现,右边部分是嵌套在一个iframe中,所以我们无法直接定位到滑块身上。
这个时候我们需要用switch_to.frame(id),来定位到右边部分。代码如下:
from selenium import webdriver
from lxml import etree
from selenium.webdriver import ActionChains
if __name__ == '__main__':
url="https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable"
bro=webdriver.Chrome("./chromedriver.exe")
bro.get(url)
#定位的目标在iframe中,必须通过以下方式进行定位
bro.switch_to_frame("iframeResult")
# 定位到待滑动的div
div = bro.find_element_by_id("draggable")
移动滑块
移动滑块需要使用到动作链。
第一步:首先要先导入相关依赖。
-from selenium.webdriver import ActionChains
第二步:实例化一个动作链对象:action = ActionChains(bro),相关api:
- click_and_hold(div):长按且点击操作
- move_by_offset(x,y)
- perform()让动作链立即执行
- action.release()释放动作链对象
示例代码:
from selenium import webdriver
from lxml import etree
from selenium.webdriver import ActionChains
if __name__ == '__main__':
url="https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable"
bro=webdriver.Chrome("./chromedriver.exe")
bro.get(url)
#定位的目标在iframe中,必须通过以下方式进行定位
bro.switch_to_frame("iframeResult")
# 定位到待滑动的div
div = bro.find_element_by_id("draggable")
#使用动作链
action=ActionChains(bro)
#长按并且点击
action.click_and_hold(div)
#开始移动
for i in range(5):
# move_by_offset(x,y) 横坐标移动17 纵坐标不动
# perform 让动作链执行
action.move_by_offset(17,0).perform()
# 释放动作链
action.release()
bro.quit()