在 jupyterlab 中使用 selenium 写入和 运行 一个代码单元

Use selenium to write in and run a code cell in jupyterlab

我想测试 juptyerlab 的补丁实现。我希望使用 selenium 在代码单元中执行 "hello world"。到目前为止,我可以登录并创建一个新笔记本:

from selenium import webdriver

driver = webdriver.Firefox()
# assume jupyterlab is running and serving on localhost at port 8888
driver.get("http://localhost:8888")
elem = driver.find_element_by_id("password_input")
password = ""
elem.send_keys(password)
elem = driver.find_element_by_id("login_submit")
elem.click()
elem = driver.find_element_by_css_selector(".jp-Launcher-cwd+ .jp-Launcher-section .jp-LauncherCard")
elem.click()

这会创建一个新笔记本,但现在我无法在单元格中输入一些代码并 运行 它。如果我查看页面源代码,我看不到单元格的任何 html 元素。但是如果我在一个单元格中输入 print("test"),那么 driver.page_source 就会包含这个(它嵌套在我也省略的其他内容中):

                                <div class="CodeMirror cm-s-jupyter CodeMirror-wrap jp-mod-readOnly">
                                    <div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 0px; left: 0px;">
                                        <textarea
                                                style="position: absolute; bottom: -1em; padding: 0px; width: 1px; height: 1em; outline: currentcolor none medium;"
                                                autocorrect="off" autocapitalize="off"
                                                spellcheck="false" tabindex="0"
                                                wrap="off"></textarea></div>
                                    <div class="CodeMirror-vscrollbar" tabindex="-1"
                                         cm-not-content="true"
                                         style="display: block; bottom: 0px;">
                                        <div style="min-width: 1px; height: 33px;"></div>
                                    </div>
                                    <div class="CodeMirror-hscrollbar" tabindex="-1"
                                         cm-not-content="true">
                                        <div style="height: 100%; min-height: 1px; width: 0px;"></div>
                                    </div>
                                    <div class="CodeMirror-scrollbar-filler"
                                         cm-not-content="true"></div>
                                    <div class="CodeMirror-gutter-filler"
                                         cm-not-content="true"></div>
                                    <div class="CodeMirror-scroll" tabindex="-1" draggable="true">
                                        <div class="CodeMirror-sizer"
                                             style="margin-left: 0px; padding-right: 0px; padding-bottom: 0px;">
                                            <div style="position: relative;">
                                                <div class="CodeMirror-lines" role="presentation">
                                                    <div style="position: relative; outline: currentcolor none medium;"
                                                         role="presentation">
                                                        <div class="CodeMirror-measure">
                                                            <pre><span>xxxxxxxxxx</span></pre>
                                                        </div>
                                                        <div class="CodeMirror-measure">
                                                            <pre class="CodeMirror-line"
                                                                 role="presentation"><span
                                                                    role="presentation"><span
                                                                    class="cm-builtin">print</span>(<span
                                                                    class="cm-string">"test"</span>)</span></pre>
                                                        </div>
                                                        <div style="position: relative; z-index: 1;"></div>
                                                        <div class="CodeMirror-cursors"></div>
                                                        <div class="CodeMirror-code"
                                                             role="presentation"></div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div style="position: absolute; height: 30px; width: 1px; border-bottom: 0px solid transparent;"></div>
                                        <div class="CodeMirror-gutters"
                                             style="display: none;"></div>
                                    </div>
                                </div>

我可以看到 print("text") 的文本在哪里(即上面 html 片段中最深的嵌套元素),但我无法弄清楚这里的哪个元素我能够将文本发送至或将密钥发送至。

我遇到了 robotframework-jupyterlibrary and it has some clues such as this and this 。从这些链接我看到

${JLAB CSS ACTIVE INPUT} ${JLAB CSS ACTIVE CELL} .CodeMirror

Add and Run JupyterLab Code Cell
    [Arguments]    ${code}=print("hello world")
    [Documentation]    Add a ``code`` cell to the currently active notebook and run it.
    Click Element    css:${JLAB CSS NB TOOLBAR} ${JLAB CSS ICON ADD}
    Sleep    0.1s
    ${cell} =   Get WebElement  css:${JLAB CSS ACTIVE INPUT}
    Click Element    ${cell}
    Set CodeMirror Value    ${JLAB CSS ACTIVE INPUT}  ${code}
    Run Current JupyterLab Code Cell
Click Element ${cell}

这让我觉得如果我 select .CodeMirror 元素,那么我只需要弄清楚 Get WebElement 在那种奇怪的语言中做了什么,以及如何在 selenium 中做到这一点。

有什么想法吗?


我也试过了(基于 and ):

from selenium.webdriver.common.action_chains import ActionChains

actions = action_chains.ActionChains(driver)
textarea = driver.find_elements_by_css_selector('.CodeMirror textarea')[0]  # tried for [0], [1] ,[2] and [3] which is all of them.
actions.move_to_element(textarea).click().send_keys("testing...").perform()

但我一直收到错误

selenium.common.exceptions.WebDriverException: Message: TypeError: rect is undefined

打开 Jupyter-Notebook:

打开命令 window 并导航到存储库文件夹或打开 anaconda-command-prompt window 并简单地执行

  • jupyter notebook --NotebookApp.token='' --NotebookApp.password=''

使用 driver.get("http://localhost:8888") 加载笔记本后,这是最棘手的部分,即如何 select 一个 Dynamically changing object。访问参考:Dynamically Changing IDs.

  • By using find_element_by_xpath
  • By using find_element_by_css_selector

这两个都会为您提供相同的 select离子点,但最好使用 Xpath,这是一种更方便的技术。你可以这样往前走;

import time
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome('chromedriver.exe')
wait = WebDriverWait(driver, 20)

driver.maximize_window()
website_url = "http://localhost:8888/"
driver.get(website_url)

# Using Xpath
# I prefer using xpath, because it is simple to understand
# and if you want to dynamically enter data into fields, it would be an awesome approach
driver.find_element_by_xpath("//div[@id='new-buttons']").click()

if len(driver.find_elements_by_xpath("//div[@id='new-buttons']//li[@id='kernel-python3']")) > 0:

   time.sleep(3)
   driver.find_element_by_xpath("//div[@id='new-buttons']//li[@id='kernel-python3']").click()

driver.find_element_by_xpath('//div[@class="cell code_cell rendered selected"]').click()

# Using css_selector
#driver.find_element_by_css_selector("#notebook-container > div").click()

command = 'print("Hello World!")'

#a = driver.find_element_by_css_selector("#notebook-container > div > div.input > div.inner_cell >"
#                                         "div.input_area > div > div:nth-child(1) > textarea")

time.sleep(3)
# To select Note-Book text-area and place command in it.
a = driver.find_element_by_xpath('//div[@class="input_area"]//textarea').click().send_keys(command)

# To run the Code in Selected Cell
time.sleep(3)
driver.find_element_by_xpath("//button[@title='Run']").click()

print("Test is done.")

以下代码已使用 Chrome、Firefox 和 jupyterlab 最新版本进行测试:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
driver.get("http://localhost:8888")
token = "0107216930d05db8a7c36ad6a73573dd5349c3dd56fee852"

wait.until(EC.element_to_be_clickable((By.ID, "password_input"))).send_keys(token, Keys.ENTER)

# wait for "Python 3" Notebook menu or CodeMirror element if already launched.
wait.until(EC.presence_of_element_located(
    (By.CSS_SELECTOR, "[title='Python 3'][data-category='Notebook'], .jp-Notebook .CodeMirror")))
# if "Python 3" Notebook menu found click to open new Notebook
if len(driver.find_elements_by_css_selector("[title='Python 3'][data-category='Notebook']")) > 0:
    driver.find_element_by_css_selector("[title='Python 3'][data-category='Notebook']").click()

# wait for CodeMirror and click to focus
code_mirror = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".jp-Notebook .CodeMirror")))
code_mirror.click()
code_mirror.find_element_by_tag_name("textarea").send_keys("print('Hello World!')")
driver.find_element_by_css_selector("[data-icon='run']").click()

output = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".jp-OutputArea-output")))
print(output.text)
assert output.text.strip() == "Hello World!"

driver.quit()