¿Cómo encontrar un elemento HTML existente con python-selenium en una página de jupyterhub?

Dec 10 2020

Tengo la siguiente construcción en una página HTML y quiero seleccionar el lielemento (con python-selenium):

<li class="p-Menu-item p-mod-disabled" data-type="command" data-command="notebook:run-all-below">
    <div class="p-Menu-itemIcon"></div>
    <div class="p-Menu-itemLabel" style="">Run Selected Cell and All Below</div>
    <div class="p-Menu-itemShortcut" style=""></div>
    <div class="p-Menu-itemSubmenuIcon"></div>
</li>

Estoy usando el siguiente xpath:

//li[@data-command='notebook:run-all-below']

Pero el elemento no parece encontrarse.

Código de ejemplo de trabajo mínimo y completo:

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("https://mybinder.org/v2/gh/jupyterlab/jupyterlab-demo/master?urlpath=lab/tree/demo")

# Wait for the page to be loaded
xpath = "//button[@title='Save the notebook contents and create checkpoint']"
element = WebDriverWait(driver, 600).until(
    EC.presence_of_element_located((By.XPATH, xpath))
)
time.sleep(10)
print("Page loaded")

# Find and click on menu "Run"
xpath_run = "//div[text()='Run']"
element = WebDriverWait(driver, 60).until(
    EC.element_to_be_clickable((By.XPATH, xpath_run))
)
element.click()
print("Clicked on 'Run'")

# Find and click on menu entry "Run Selected Cell and All Below"
xpath_runall = "//li[@data-command='notebook:run-all-below']"
element = WebDriverWait(driver, 600).until(
    EC.element_to_be_clickable((By.XPATH, xpath_runall))
)
print("Found element 'Run Selected Cell and All Below'")
element.click()
print("Clicked on 'Run Selected Cell and All Below'")

driver.close()

Medio ambiente:

  • MacOS Mojave (10.14.6)
  • pitón 3.8.6
  • selenio 3.8.0
  • geckodriver 0.26.0

Apéndice

He estado intentando registrar los pasos con el complemento "Selenium IDE" de Firefox, que proporciona los siguientes pasos para Python:

sdriver.get("https://hub.gke2.mybinder.org/user/jupyterlab-jupyterlab-demo-y0bp97e4/lab/tree/demo")
driver.set_window_size(1650, 916)
driver.execute_script("window.scrollTo(0,0)")
driver.find_element(By.CSS_SELECTOR, ".lm-mod-active > .lm-MenuBar-itemLabel").click()

que, por supuesto, tampoco funciona. Con esas líneas de código me sale un error

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .lm-mod-active > .lm-MenuBar-itemLabel

Respuestas

4 DebanjanB Dec 18 2020 at 02:37

Estabas lo suficientemente cerca. De hecho, todo su programa tuvo un solo problema de la siguiente manera:

  • El xpath_runall = "//li[@data-command='notebook:run-all-below']"no identifica el elemento visible con texto Ejecutar la celda seleccionada y todos Debajo de forma única como el primer elemento emparejado es un escondido elemento.

Consideraciones adicionales

Algunas optimizaciones más:

  • El elemento identificado como xpath = "//button[@title='Save the notebook contents and create checkpoint']"es un elemento en el que se puede hacer clic . Entonces, en lugar de EC como presence_of_element_located()puedes usarelement_to_be_clickable()

  • Una vez que el elemento se devuelve a través de EC , element_to_be_clickable()puede invocarlo click()en la misma línea.

  • El xpath para identificar el elemento con texto como Ejecutar celda seleccionada y Todo a continuación sería:

    //li[@data-command='notebook:run-all-below']//div[@class='lm-Menu-itemLabel p-Menu-itemLabel' and text()='Run Selected Cell and All Below']
    
  • Como la aplicación está construida a través de JavaScript , necesita usar ActionChains .


Solución

Tu solución optimizada será:

  • Bloque de código:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.action_chains import ActionChains
    
    driver = webdriver.Firefox(executable_path=r'C:\WebDrivers\geckodriver.exe')
    driver.get("https://mybinder.org/v2/gh/jupyterlab/jupyterlab-demo/master?urlpath=lab/tree/demo")
    WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.XPATH, "//button[@title='Save the notebook contents and create checkpoint']")))
    print("Page loaded")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[text()='Run']"))).click()
    print("Clicked on Run")
    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//li[@data-command='notebook:run-all-below']//div[@class='lm-Menu-itemLabel p-Menu-itemLabel' and text()='Run Selected Cell and All Below']")))
    ActionChains(driver).move_to_element(element).click(element).perform()
    print("Clicked on Run Selected Cell and All Below")
    
  • Salida de consola:

    Page loaded
    Clicked on Run
    Clicked on Run Selected Cell and All Below
    
3 Booboo Dec 17 2020 at 23:21

Esto funcionó para mí. Encuentro el elemento del menú de nivel superior usando xpath completo y luego hago clic en él. Espero un poco de tiempo para asegurarme de que ha aparecido el menú emergente y luego, usando un desplazamiento del elemento del menú original que he predeterminado, muevo el mouse a ese desplazamiento y hago clic en lo que sé que es el sub- opción del menú. En el siguiente código, primero me doy la oportunidad de seleccionar una celda:

driver.implicitly_wait(300) # wait up to 300 seconds before calls to find elements time out
driver.get('https://mybinder.org/v2/gh/jupyterlab/jupyterlab-demo/master?urlpath=lab/tree/demo')
driver.execute_script("scroll(0, 0);")
elem = driver.find_element_by_xpath('//div[text()="Run"]')
elem.click() # click on top-level menu item
time.sleep(.2) # wait for sub-menu to appear
action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(elem, 224, 182)
# click on sub-menu item:
action.click()
action.perform()

Actualización: una solución más óptima

driver.implicitly_wait(300) # wait up to 300 seconds before calls to find elements time out
driver.get('https://mybinder.org/v2/gh/jupyterlab/jupyterlab-demo/master?urlpath=lab/tree/demo')
driver.execute_script("scroll(0, 0);")
elem = driver.find_element_by_xpath('//div[text()="Run"]')
elem.click()
driver.implicitly_wait(.2)
elem2 = driver.find_element_by_xpath('//*[contains(text(),"Run Selected Cell and All Below")]')
driver.execute_script("arguments[0].click();", elem2) # sub-menu, however, stays open
# to close the sub-menu menu:
elem.click()
1 KunduK Dec 10 2020 at 19:58

Parece que hay dos elementos li con atributos similares. Necesita identificar el elemento correcto para xpathhacer clic. Utilice lo siguiente para hacer clic en el elemento correcto.

xpath_runall = "//ul[@class='lm-Menu-content p-Menu-content']//li[@data-command='notebook:run-all-below']"
element = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, xpath_runall))
)
elementText=element.text
print("Found element '{}'".format(elementText))
element.click()
print("Clicked on '{}'".format(elementText))

Salida de consola:

Page loaded
Clicked on 'Run'
Found element 'Run Selected Cell and All Below'
Clicked on 'Run Selected Cell and All Below'