selenium 鼠標點擊操作比較簡單,這里就不介紹了,主要說一下鼠標滑動(按住並滑動),經常用於解決自動化操作的滑動驗證碼
下面舉個簡單的例子,比如這種驗證碼:
代碼:
div = driver.find_element_by_id("nc_1_n1z")
ActionChains(driver).click_and_hold(on_element=div).perform()
time.sleep(0.15)
ActionChains(driver).move_to_element_with_offset(to_element=div, xoffset=30, yoffset=10).perform()
time.sleep(1)
ActionChains(driver).move_to_element_with_offset(to_element=div, xoffset=100, yoffset=20).perform()
time.sleep(0.5)
ActionChains(driver).move_to_element_with_offset(to_element=div, xoffset=200, yoffset=50).perform()
筆者親測是可以的,不過為了確保一定過 把一次滑動分為三段,還可以進一步優化,把每次滑動的距離和間隔時間做隨機
但是筆者又遇到一個問題,在同一個文件里面 下面的程序還要做一次滑動操作,發現無法滑動,debug跟蹤發現,下面的滑動並沒有起作用
原因:因為上面的操作 沒有釋放鼠標,那么如何釋放鼠標呢?官方只說了 release()方法,具體如何使用,看代碼
div = driver.find_element_by_id("nc_1_n1z")
ActionChains(driver).click_and_hold(on_element=div).perform()
time.sleep(0.15)
ActionChains(driver).move_to_element_with_offset(to_element=div, xoffset=30, yoffset=10).perform()
time.sleep(1)
ActionChains(driver).move_to_element_with_offset(to_element=div, xoffset=100, yoffset=20).perform()
time.sleep(0.5)
ActionChains(driver).move_to_element_with_offset(to_element=div, xoffset=200, yoffset=50).release().perform()
PS:在做鼠標滑動操作時,都是在這個地方寫操作函數
比如你要根據相對某個元素偏移坐標處做點擊操作
ActionChains(driver).move_to_element_with_offset(to_element=div, xoffset=200, yoffset=50).click().perform()--這里不是按住滑動,不需要釋放鼠標
該操作可用於解決點擊類的驗證碼,比如: