【发布时间】:2020-07-16 17:39:14
【问题描述】:
我只是将 selenium 机器人作为一个有趣的项目,它应该为我玩 typeracer,我在让它等待倒计时完成后再尝试开始打字时遇到了一些麻烦。我发现做到这一点的最好方法是等待文本输入字段可编辑,而不是等待倒计时弹出窗口消失,但正如我之前所说,除非我使用,否则我不能让它等待一个 time.sleep() 函数。这不会很好地工作,因为我们可能必须等待 5 到 12 秒的时间才能启动机器人,因此它可能等待的时间太长或不够长。我已经尝试了许多其他类似问题的解决方案,例如this one,但到目前为止没有任何效果。
这是我目前的代码:
#!/usr/bin/env/python3
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class TRBot:
def __init__(self, username, passwd):
self.username = username
self.driver = webdriver.Safari()
self.driver.get("https://play.typeracer.com") # Open automated safari to typeracer
time.sleep(2)
self.driver.find_element_by_xpath("//a[@title=\"Keyboard shortcut: Ctrl+Alt+I\"]").click() # Click the "Enter a typing race" button
time.sleep(2)
inputField = WebDriverWait(self.driver, 10).until(EC.visibility_of((By.XPATH, "<div contenteditable=\"plaintext-only\"></div>")))
# Find the first word of the passage to type
text = self.driver.find_element_by_xpath("//*[@id=\"gwt - uid - 15\"]/table/tbody/tr[2]/td/table/tbody/tr[1]/td/table/tbody/tr[1]/td/div/div/span[1]").get_attribute("innerHTML")
while text != "":
inputField.send_keys(text) # Type the word
text = self.driver.find_element_by_xpath("//*[@id=\"gwt - uid - 15\"]/table/tbody/tr[2]/td/table/tbody/tr[1]/td/table/tbody/tr[1]/td/div/div/span[1]").get_attribute("innerHTML") # Find the next word
time.sleep(5)
self.driver.quit()
TypeRacerBot = TRBot("TRBot", "R0b0t@")
这是错误输出:
Traceback (most recent call last):
File "/Users/myuser/Documents/Programming/Python/TypeRacerBot.py", line 45, in <module>
TypeRacerBot = TRBot("TRBot", "R0b0t@")
File "/Users/myuser/Documents/Programming/Python/TypeRacerBot.py", line 29, in __init__
inputField = WebDriverWait(self.driver, 10).until(EC.visibility_of((By.XPATH, "<div contenteditable=\"plaintext-only\">\*</div>")))
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/selenium/webdriver/support/wait.py", line 71, in until
value = method(self._driver)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/selenium/webdriver/support/expected_conditions.py", line 144, in __call__
return _element_if_visible(self.element)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/selenium/webdriver/support/expected_conditions.py", line 148, in _element_if_visible
return element if element.is_displayed() == visibility else False
AttributeError: 'tuple' object has no attribute 'is_displayed'
现在,直到 inputField = WebDriverWait(... 行之前,一切都按预期工作,所以这就是我目前专注于修复的内容,但如果您在代码中看到任何无法进一步工作的内容,我也愿意接受那里的建议.
提前致谢!
【问题讨论】:
标签: python-3.x selenium selenium-webdriver webdriverwait