代码之家  ›  专栏  ›  技术社区  ›  compx

当尝试使用Selenium选择svg时,NoSuchElements存在

  •  0
  • compx  · 技术社区  · 2 月前

    我有很多文件要下载,所以我试图用python和Selenium自动化它。(访问网站的API不是一种选择;如果可以的话,我会这么做的。)

    我无法让脚本找到的唯一元素是实际的下载按钮。(无论使用何种方法识别,我都会收到“NoSuchElementExists”错误。)

    这是带有两个按钮的父元素。第二个是我想选择的。

    <div class="Transactions_csvButtonsContainer__dhv_J">
    <svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg">
    <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
    <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
    </svg>
    <svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg">
    <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line>
    </svg>
    </div>
    

    我在Firefox和Chrome中都进入了F12开发者模式,复制了元素的XPATH和CSS选择器查询,并将其粘贴到以下代码中:

    download_button = driver.find_element(by=By.XPATH, value=
        "//*[@id='__next']/div/div[3]/div[1]/a[1]/div/div[1]/div[2]/svg[2]")
    download_button = driver.find_element(by=By.CSS_SELECTOR, value=
        "div.Transactions_bubblesAndCSVContainer__RxEX5: nth - child(1) > div:nth - child(2) > svg: nth - child(2)")
    

    我对这两种方法都不感兴趣,因为它们都很脆弱。父元素(div)不可交互。我如何让这个脚本识别下载按钮?

    1 回复  |  直到 2 月前
        1
  •  1
  •   dann    2 月前

    在这种错误中,我建议使用XPath和显式等待来处理它。尝试首先导入所有需要的包:

    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
    

    现在,初始化驱动程序。我在用Chrome,所以:

    driver = webdriver.Chrome()
    driver.get('URL_OF_YOUR_PAGE')  # Replace with the actual URL
    

    最后,等待元素出现并可交互:

    try:
        # wait for the container div to be present
        wait = WebDriverWait(driver, 10)
        container = wait.until(EC.presence_of_element_located(
            (By.CLASS_NAME, 'Transactions_csvButtonsContainer__dhv_J')))
    
        # find the second SVG element within the container
        download_button = container.find_elements(By.TAG_NAME, 'svg')[1]
        
        # click the download button
        download_button.click()
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        driver.quit()
    

    我正在使用异常处理,所以如果发生任何错误并且这些步骤无法工作,您可以尝试调试或其他策略。请随时更新,希望对我有所帮助!