我使用Selenium webdriver在webdriver中使用以下代码编写具有一些特殊功能的文本:
def typing_(self, text):
time.sleep(1)
new_text = []
text_ = text.split(' ')
for word in text_:
new_text.append(word + ' ')
if word.startswith('@') or word.startswith('&'):
new_text.append(self.enter_key)
# new_text is the result of parsing text and adding the function
time.sleep(1)
actions = ActionChains(self.driver)
for word_ in new_text:
if not isinstance(word_, str):
word_()
time.sleep(1)
else:
for char in word_:
actions.send_keys(char[0])
actions.perform()
time.sleep(1)
它所做的就是输入一些文本并将其写入
我还添加了一个特殊的特性:当字符"@"或",",它会计算下一个字符,直到找到一个空格",在它之前按回车键。
在这种情况下,我配置了一个函数press_enter(),所以这部分会很容易。
的例子:
我认为@guacamole(按回车键)对健康有好处
当我将文本发送到webdriver时,我得到的结果如下:注意:它实际上是在正确的位置按下回车键
II I tI thI thiI thinI thinkI think I think @I think @gI think @guI think @guaI think @guacI think @guacaI think @guacamI think @guacamoI think @guacamolI think @guacamoleI think @guacamole
I think @guacamole iI think @guacamole isI think @guacamole is I think @guacamole is gI think @guacamole is goI think @guacamole is gooI think @guacamole is goodI think @guacamole is good I think @guacamole is good fI think @guacamole is good foI think @guacamole is good forI think @guacamole is good for I think @guacamole is good for hI think @guacamole is good for heI think @guacamole is good for heaI think @guacamole is good for healI think @guacamole is good for healtI think @guacamole is good for healthI think @guacamole is good for health
def typing_(self, text):
time.sleep(1)
new_text = []
text_ = text.split(' ')
for word in text_:
new_text.append(word + ' ')
if word.startswith('@') or word.startswith('&'):
new_text.append(self.enter_key)
# new_text is the result of parsing text and adding the function
time.sleep(1)
actions = ActionChains(self.driver)
for word_ in new_text:
if not isinstance(word_, str):
word_()
time.sleep(1)
else:
for char in word_:
actions.send_keys(char[0])
actions.perform()
actions.reset_actions()
time.sleep(1)
尝试在forloop中添加reset_actions,否则该操作将链接之前的发送键操作
如果这不起作用,则使用以下两种解决方案中的任何一种:
首先将动作初始化到循环内部:
for char in word:
actions = webdriver.ActionChains(driver)
actions.send_keys(char[0])
actions.perform()
time.sleep(1)
**更新到alpha v4**
pip install selenium==4.0.0.a7
对于第二个解决方案,您的代码将像
一样工作更多信息:
https://github.com/SeleniumHQ/selenium/issues/6837
reset_actions()没有重置操作。
这个有一个bug,在最新的seleniumv4
中修复了在selenium v3中,您可以使用上面提到的修复或for char in word:
actions.send_keys(char[0])
time.sleep(1)
actions.perform()
actions.w3c_actions.clear_actions()
for device in actions.w3c_actions.devices:
device.clear_actions()