首页 > 解决方案 > Python Selenium send_keys() 更改文本格式(缩进)

问题描述

我正在使用 Selenium 将数据输入到一些文本字段中。我遇到了 的奇怪行为send_keys(),更改了我发送的字符串的一些格式。

我通过 Pyperclip 使用 Copy-Paste 解决了这个问题,它工作正常,没有更改我的字符串中的任何缩进并且由于不正确的缩进而导致错误。

仍然希望在没有我的剪贴板解决方法的情况下了解解决此问题的正确方法。

driver.find_element(By.CSS_SELECTOR, ".CodeMirror textarea").send_keys(Keys.CONTROL + "a");
driver.find_element(By.CSS_SELECTOR, ".CodeMirror textarea").send_keys(Keys.DELETE);

# driver.find_element(By.CSS_SELECTOR, ".CodeMirror textarea").send_keys(htmlFromTxt[x - 1])
# formatting bug fix
pp.copy(htmlFromTxt[x - 1])
driver.find_element(By.CSS_SELECTOR, ".CodeMirror textarea").send_keys(Keys.CONTROL + "v");

原始和正确的字符串:

<problem>
  <customresponse cfn="check_function">
    <script type="loncapa/python">

import json
def check_function(e, ans):
  """
  "response" is a dictionary that contains two keys, "answer" and "state".
  The value of "answer" is the JSON string that "getGrade" returns.
  The value of "state" is the JSON string that "getState" returns.
  Clicking either "Submit" or "Save" registers the current state.
  """
  response = json.loads(ans)

  # You can use the value of the answer key to grade:
  answer = json.loads(response["answer"])
  state = json.loads(response["state"])
  return answer &gt;= 0;

</script>

通过 send_keys() 格式错误:

<problem>
    <customresponse cfn="check_function">
      <script type="loncapa/python">

        import json
        def check_function(e, ans):
          """
          "response" is a dictionary that contains two keys, "answer" and "state".
          The value of "answer" is the JSON string that "getGrade" returns.
          The value of "state" is the JSON string that "getState" returns.
          Clicking either "Submit" or "Save" registers the current state.
          """
          response = json.loads(ans)

          # You can use the value of the answer key to grade:
          answer = json.loads(response["answer"])
          state = json.loads(response["state"])
          return answer &gt;= 0;     

      </script>

标签: python-3.xstringseleniumtextpyperclip

解决方案


推荐阅读