[Python] With Selenium, how can I find an element by CSS Selector that has to wait for the...

Discussão em 'Python' iniciado por Stack, Maio 21, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using Selenium to loop through a patient's folders on a hospital's web portal and download all of the PDF files inside each folder. Here is a screenshot of the folders list:

    [​IMG]

    Using Visit #269977 as an example, when I click on the Options link below each folder, a menu pops up with options:

    [​IMG]

    I want Selenium to click the Print option. I can find the element by its XPATH for a specific folder, however that is not useful when I begin looping through folders, as I'm unsure what the index is of each list item. Ideally I'd use the CSS Selector, but the element doesn't seem to be visible.

    [​IMG]

    Here's what the DOM tree looks like prior to Selenium clicking on Options:

    [​IMG]

    Here's what the DOM tree looks like after Selenium clicks on Options:

    [​IMG]

    How can I ensure the Print option can be located by CSS Selector (or another viable alternative) so that I can click on it?

    In the code below I've included multiple things I've tried. Each returns an error saying the element can't be found. Happy to provide additional information. Thanks!

    #selenium verson == 4.27.1
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.wait import WebDriverWait
    import time

    # Initial Login:
    chrome_options = Options()
    chrome_options.add_experimental_option("detach", True)
    browser = webdriver.Chrome(options=chrome_options)

    # Code logs into browser and enters patient name to get to the following screen:

    visit_id = '269977'

    items = browser.find_elements(By.XPATH, "//*['/html/body/div[1]/div[4]/div[3]/div[2]/ul/li' and contains(text(),"+ visit_id +")]")

    for item in items:
    x = item.find_elements(By.XPATH, ".//descendant::a")
    for y in x:
    y.click()

    # Options I've tried:

    # Working XPATH:
    printVisit = y.find_element(By.XPATH, "//*[@id='documentlist']/li[5]/div[5]/a[5]")

    # Not working CSS/CLASS Selectors:
    WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='tools open']")))

    printVisit = y.find_element(By.XPATH, "//div[@class='tool print']")
    printVisit = y.find_element(By.LINK_TEXT, 'Print')
    printVisit = WebDriverWait(y, 5).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, 'tool print')))

    # This one was working yesterday and then stopped suddenly:
    printVisit = WebDriverWait(y,10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, '.tool print')))

    Continue reading...

Compartilhe esta Página