如何通过Actionchains send_keys像人一样打字

时间:2018-08-02 10:48:16

标签: python python-3.x selenium sendkeys

我知道如何用下一个代码缓慢键入:

elem = driver.find_element_by_id("mainCommentForm")
text = "To type text here"
for character in text:
  elem.send_keys(character)
  time.sleep(random.uniform(0.2,0.5))

不幸的是,我使用的网站不允许通过正常的send_keys选项键入文本,因为它会显示错误消息。就像我选择了元素,然后要send_keys一样,但是由于取消选择元素或其他原因,它找不到元素。它与在Java中键入有关。请不要问为什么这不起作用,因为那不是我的问题。

事实是,我需要使用Actionchains send_keys选项,如下所示。 但是,如何像上面的示例一样模拟现在作为人类的打字? 人工输入是指逐个字母输入,而不仅仅是复制/粘贴。

elem = driver.find_element_by_id("mainCommentForm")
actions = ActionChains(driver)
actions.move_to_element(elem)
actions.click()
actions.send_keys("This text must be typed in slower..")
actions.perform()

2 个答案:

答案 0 :(得分:2)

此代码以您想要的方式工作-

elem = driver.find_element_by_id("mainCommentForm")
text = "To type text here"
for character in text:
  actions = ActionChains(driver)
  actions.move_to_element(elem)
  actions.click()
  actions.send_keys(character)
  print(character)
  actions.perform()
  time.sleep(random.uniform(0.2,0.5))

答案 1 :(得分:0)

在python中,如果您想键入类似真实人类的文字,只需使用此代码,每个字符之间的交易就会是随机的

 for char in text:
        start = 0.1 #please edit the speed here
        stop = 0.6 #change this (the maximum value is 1 or 0.9)
        step = 0.3
        precision = 0.1
        f = 1 / precision
        n = random.randrange(start * f, stop * f, step * f) / f
        time.sleep(n)
        user_input.send_keys(char)