【问题标题】:Python Selenium Chrome Webdriver: interacti with a gamePython Selenium Chrome Webdriver:与游戏交互
【发布时间】:2020-05-03 12:36:46
【问题描述】:

我在与网站交互时遇到问题。对我来说,这是我第一次使用 Python 来做这样的事情。我想写一个代码来玩这个链接中的游戏:https://www.coolmathgames.com/0-worlds-hardest-game。 我尝试使用此代码在游戏中移动玩家,但结果是网页滚动并且玩家没有移动。

import random
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get('https://www.coolmathgames.com/0-worlds-hardest-game')

moves = [Keys.LEFT, Keys.DOWN, Keys.RIGHT, Keys.UP]
time.sleep(10)
i = 0
while i < 100:
    time.sleep(0.1)
    driver.find_element_by_css_selector('html').send_keys(random.choice(moves))
    i += 1

(插入time.sleep(10)指令是为了让我手动进入游戏)

哪些代码用于与游戏交互而不仅仅是与网站页面交互?

【问题讨论】:

  • 检查下面的答案。这就是你需要做的。由于它是一个具有特殊属性和元素的平台,因此可能会出现技术问题,但与游戏交互的逻辑是下面答案中的逻辑。希望我对你有帮助:)

标签: python python-3.x selenium web selenium-webdriver


【解决方案1】:

游戏在 iframe 中。您必须进入 iframe 并相应地操作 iframe 的实例。

查看我从您插入问题的链接中截取的以下屏幕截图:

以下是如何输入 iframe 的示例:

driver = webdriver.Chrome()

## Enter into the iframe
driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))

# Locate and do whatever you want inside the iframe (all the tags or attributes must be sub-attributes of this iframe tag)
element = driver.find_element_by_xpath("/html/body/p")

# If you don't want to do anything else inside the iframe and you want to do something in the platform (outside of the game) then you need to quit from the iframe and switch to the default content by executing the following line
driver.switch_to.default_content()

如果您需要其他详细信息,请查看Selenium的官方文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多