Como encontrar um elemento HTML existente com python-selenium em uma página jupyterhub?
Eu tenho a seguinte construção em uma página HTML e quero selecionar o li
elemento (com 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>
Estou usando o seguinte xpath:
//li[@data-command='notebook:run-all-below']
Mas o elemento não parece ser encontrado.
Código de exemplo completo e mínimo funcional:
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()
Meio Ambiente:
- MacOS Mojave (10.14.6)
- python 3.8.6
- selênio 3.8.0
- geckodriver 0.26.0
Termo aditivo
Tenho tentado registrar as etapas com o complemento "Selenium IDE" do Firefox, que fornece as seguintes etapas 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()
o que, claro, também não funciona. Com essas linhas de código, recebo um erro
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .lm-mod-active > .lm-MenuBar-itemLabel
Respostas
Você estava perto o suficiente. Na verdade, todo o seu programa teve apenas um único problema, como segue:
- O
xpath_runall = "//li[@data-command='notebook:run-all-below']"
não identifica o elemento visível com texto como Executar célula selecionada e Todos abaixo exclusivamente, pois o primeiro elemento correspondente é um elemento oculto .
Considerações adicionais
Mais algumas otimizações:
O elemento identificado como
xpath = "//button[@title='Save the notebook contents and create checkpoint']"
é um elemento clicável . Então, em vez de EC ,presence_of_element_located()
você pode usarelement_to_be_clickable()
Assim que o elemento for retornado por meio de EC ,
element_to_be_clickable()
você pode invocar oclick()
na mesma linha.O xpath para identificar o elemento com texto como Run Selected Cell e All Below seria:
//li[@data-command='notebook:run-all-below']//div[@class='lm-Menu-itemLabel p-Menu-itemLabel' and text()='Run Selected Cell and All Below']
Como o aplicativo é construído por meio de JavaScript, você precisa usar ActionChains .
Solução
Sua solução otimizada será:
Bloco 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")
Saída do console:
Page loaded Clicked on Run Clicked on Run Selected Cell and All Below
Isso funcionou para mim. Eu encontro o item de menu de nível superior usando o xpath completo e clico nele. Espero um pouco para garantir que o menu pop-up apareça e, em seguida, usando um deslocamento do item de menu original que predeterminei, movo o mouse para esse deslocamento e clico no que sei ser o sub- item do menu. No código abaixo, primeiro me dou a chance de selecionar uma célula:
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()
Atualização: uma solução mais ideal
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()
Parece que existem dois elementos li com atributos semelhantes. Você precisa identificar o elemento correto para clicar. Use o seguinte xpath
para clicar no elemento correto.
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))
Saída do console:
Page loaded
Clicked on 'Run'
Found element 'Run Selected Cell and All Below'
Clicked on 'Run Selected Cell and All Below'