在 codemirror python selenium 的文本区域中输入文本

Input text into textarea for codemirror python selenium

我是 selenium 的新手,正在尝试将文本输入到 CodeMirror 生成的文本区域中。我查看了 textarea 上的其他问题,但无法解决我的问题。

我正在使用 Chrome 并且在文本区域所在的源中找到了并且能够单击它使光标闪烁。但是,我发现它没有任何属性。如何将文本输入文本区域?我尝试了其他元素,但遇到了 "can't focus" 或 "not visible" 错误,我猜这意味着这些元素不是文本区域。

a= browser.find_element_by_css_selector('div.CodeMirror.CodeMirror-wrap.dojoDndTarget.cm-s-sql.dojoDndContainer').click()
print a
None

我知道添加长源代码可能会给其他用户带来不便,但我不确定哪一行 CodeMirror 可能引用了文本区域,为了完整起见,我将其发布。这是源代码和屏幕截图。

<div class="CodeMirror CodeMirror-wrap dojoDndTarget cm-s-sql dojoDndContainer" style="font-size: 12px; font-weight: normal;">
<div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 4px; left: 4px;">
<textarea autocorrect="off" autocapitalize="off" spellcheck="false" style="position: absolute; padding: 0px; width: 1000px; height: 1em; outline: none;" tabindex="0">
</textarea>
</div>
<div class="CodeMirror-vscrollbar" not-content="true" style="min-width: 18px;">
<div style="min-width: 1px; height: 0px;">
</div>
</div>
<div class="CodeMirror-hscrollbar" not-content="true" style="min-height: 18px;">
<div style="height: 100%; min-height: 1px; width: 0px;">
</div>
</div>
<div class="CodeMirror-scrollbar-filler" not-content="true">
</div>
<div class="CodeMirror-gutter-filler" not-content="true">
</div>
<div class="CodeMirror-scroll" tabindex="-1">
<div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 30px; min-height: 24px; padding-right: 0px; padding-bottom: 0px;">
<div style="position: relative; top: 0px;">
<div class="CodeMirror-lines">
<div style="position: relative; outline: none;">
<div class="CodeMirror-measure">
</div>
<div class="CodeMirror-measure">
</div>
<div style="position: relative; z-index: 1;">
</div>
<div class="CodeMirror-cursors" style="">
<div class="CodeMirror-cursor" style="left: 4px; top: 0px; height: 16px;">&nbsp;</div></div><div class="CodeMirror-code">
<pre class="">
<span style="padding-right: 0.1px;">
<span>
</span>
</span>
</pre>
</div>
</div>
</div>
</div>
</div>
<div style="position: absolute; height: 30px; width: 1px; top: 24px;"></div><div class="CodeMirror-gutters" style="display: none; height: 197px;">
</div>
</div>
</div>

谢谢。

在 Selenium 中,WebElement#click() 没有 return 任何东西。如果你想在点击后与元素对象进一步交互,你需要先将其保存到一个变量中。

但更重要的是,您单击的是 包含 <textarea><div> 而不是 <textarea> 本身。即使单击 <div> 获得 <textarea> 焦点,您的元素对象仍将是包含 <div> 的句柄,它不会对 send_keys() 做出有意义的反应。如果 <textarea> 是用户输入文本的地方,您必须找到 that 元素并与之交互:

textarea = browser.find_element_by_css_selector('.CodeMirror textarea')

(除非 <textarea> 被禁用并且需要额外的步骤才能启用它,否则您不需要 click() 它就可以开始输入。)

然后简单地send_keys()就可以了:

textarea.send_keys('alert("Hello, World!")')