Selenium Python 中的 Action Chains:基於偏移量的拖放方法
基於偏移量的拖放方法是使用 Selenium 的 Action Chains API 執行的。它類似於簡單的拖放,但額外使用了物件的偏移量來建立功能。在本文中,我們將使用 Selenium Python 中的 Action Chains 建立基於偏移量的拖放功能。
什麼是基於偏移量的拖放方法?
基於偏移量的拖放方法是一種操作,它使用元素的偏移位置將元素從一個位置拖動到另一個位置。Action Chains 提供了一個 `drag_and_drop_by_offset()` 方法,它接受兩個引數:一個是要拖動的元素,另一個是 x 和 y 偏移值。
x 和 y 偏移值分別指定元素在水平和垂直方向上要移動的畫素數。偏移值是相對於元素當前位置的相對值。例如,如果元素的當前位置是 (x1, y1),偏移值是 (dx, dy),則拖動操作後元素的新位置將是 (x1+dx, y1+dy)。
示例
在下面的示例中,我們使用 `drag_and_drop_by_offset` 方法移動 jQuery UI 網站上的滑塊。我們首先導航到 jQuery UI 網站,然後切換到包含滑塊元素的 iframe。然後,我們使用 `find_element` 方法定位滑塊元素,並建立 ActionChains 的例項。然後,我們兩次連結 `drag_and_drop_by_offset` 操作,分別將滑塊控制代碼向右移動 50 畫素,然後向左移動 50 畫素。
from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By # Create a new Chrome browser instance driver = webdriver.Chrome() # Navigate to the jQuery UI website driver.get("https://jqueryui.com/slider/") # Switch to the iframe containing the slider element driver.switch_to.frame(driver.find_element(By.CSS_SELECTOR, ".demo-frame")) # Find the slider element slider_frame = driver.find_element(By.CSS_SELECTOR, "#slider") slider = slider_frame.find_element(By.CSS_SELECTOR, ".ui-slider-handle") # Create an instance of ActionChains action_chains = ActionChains(driver) # Chain the drag and drop action with an offset of (50, 0) pixels # to move the slider handle to the right by 50 pixels action_chains.drag_and_drop_by_offset(slider, 50, 0).perform() # Chain the drag and drop action with an offset of (-50, 0) pixels # to move the slider handle back to the left by 50 pixels action_chains.drag_and_drop_by_offset(slider, -50, 0).perform() # Close the browser window driver.quit()
輸出
結論
在本文中,我們討論了使用 Selenium Python 中的 Action Chains 實現基於偏移量的拖放方法。基於偏移量的拖放方法用於執行操作,使用元素的偏移位置將元素從一個位置拖動到另一個位置。
廣告