我目前正在使用一个脚本来自动完成游戏little alchemy 2。
随着游戏的进行,已经发现的物品的库会增加,最终您必须滚动才能找到一些较低的物品。
当我尝试抓住的项目不在屏幕上时,Selenium会引发异常MoveTargetOutOfBoundsException
。
我试图通过捕获异常来解决此问题,然后使用move_to_element
使该物品到达Selenium的范围。但是当我尝试时,什么也没发生。有任何想法吗?
try:
ActionChains(driver).drag_and_drop(elempic2, workspace).perform()
except MoveTargetOutOfBoundsException:
print ("Need to Scroll because if element 2")
ActionChains(driver).move_to_element(elempic2).perform()
ActionChains(driver).drag_and_drop(elempic2, workspace).perform()
print ("Element 2 dragged: " + str(elemname2.text))
引发的错误:
Traceback (most recent call last):
File "littlealch.py", line 60, in findelements
ActionChains(driver).drag_and_drop(elempic2, workspace).perform()
File "/home/joco/.local/lib/python3.6/site-packages/selenium/webdriver/common/action_chains.py", line 80, in perform
self.w3c_actions.perform()
File "/home/joco/.local/lib/python3.6/site-packages/selenium/webdriver/common/actions/action_builder.py", line 76, in perform
self.driver.execute(Command.W3C_ACTIONS, enc)
File "/home/joco/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/joco/.local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.MoveTargetOutOfBoundsException: Message: (1624, 957.5) is out of bounds of viewport width (1920) and height (942)
如果您想自己尝试一下,here是仓库。
谢谢您的帮助:)
答案 0 :(得分:0)
我会将滚动逻辑转换为不需要显示目标元素的东西,例如沿着这些方向的东西:
y_position = 0
searching = True
while searching:
try:
ActionChains(driver).drag_and_drop(elempic2, workspace).perform()
searching = False
except MoveTargetOutOfBoundsException:
y_position += 500
driver.execute_script('window.scrollTo(0, ' + str(y_position) + ');')
print ('Element 2 dragged: ' + str(elemname2.text))
这只是使用JavaScript向下滚动页面,直到可以执行工作为止。