day03 元素交互操作
from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys #键盘按键操作 import time driver = webdriver.Chrome() try: driver.implicitly_wait(10) driver.get('http://www.jd.com/') time.sleep(5) #点击 清除 input = driver.find_element_by_id('key') input.send_keys('围城') #通过class查找搜索按钮 search = driver.find_element_by_class_name('button') search.click() #点击搜索按钮 time.sleep(3) input2 = driver.find_element_by_id('key') input2.clear() #清空输入框 time.sleep(1) input2.send_keys('墨菲定律') input2.send_keys(Keys.ENTER) time.sleep(10) finally: driver.close()
from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys #键盘按键操作 import time driver = webdriver.Chrome() try: driver.implicitly_wait(10) driver.get('https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable') time.sleep(5) #获取动作对象 action = ActionChains(driver) #iframe 切换 # driver.switch_to_frame() driver.switch_to.frame('iframeResult') time.sleep(1) src = driver.find_element_by_id('draggable') tge = driver.find_element_by_id('droppable') #方式一:秒移 #拟定好了一个动作,需要调用执行方法(perform) # action.drag_and_drop(src,tge).perform() # time.sleep(10) #方式二:缓慢移动(防反爬) #1.找滑块的移动位置和距离 #找到滑动距离 # src.location 位置(xy坐标) # src.size 大小 # src.text 文本 # src.tag_name 名称 #滑动距离 distance = tge.location['x'] - src.location['x'] #点住目标 ActionChains(driver).click_and_hold(src).perform() s = 0 while s < distance: ActionChains(driver).move_by_offset(xoffset=2,yoffset=0).perform() s += 2 time.sleep(0.1) #松开滑块 ActionChains(driver).release() finally: driver.close()