Selenium Can't Find element by Xpath?

Question:

I’m trying to click a button to automatically export a csv file from this site. I’ve tried finding the element by button name and by Xpath, but the "NoSuchElement" Exception is raised. I’ve tried variations of WebdriverWait and time.sleep to ensure the button loads, and used the xPath finder extension to get the right xPath.

Code is as follows:

#import Packages
import selenium
import time
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

#set URL, Get it, and wait
driver = webdriver.Chrome()
driver.get('https://www.egle.state.mi.us/RIDE/inventory-of-facilities/facilities')
WebDriverWait(driver,11)

#Set and Click button 
button = driver.find_element(by=By.XPATH, value='//*[@id="maincontent"]/div/inventory-of-facilities/som-page-section/div/div[2]/div[2]/facilities-table/som-page-section/div/div[2]/div[2]/som-table/div/div/div[1]/div[2]/div[2]/button')
button.click()

The button I’m trying to access is shown in image below: enter image description here
Before posting I’ve referenced the following Questions:

  1. Clicking a button with Selenium button
  2. How to press/click the button using Selenium if the button does not have the Id?
  3. AttributeError: 'WebDriver' object has no attribute 'find_element_by_xpath'

*new to Selenium and not well versed in HTML. Any insight is much appreciated.

Asked By: TidyBigfoot22

||

Answers:

I was able to click that button using SeleniumBase.

pip install seleniumbase, save the following script to a file, and then run with python or pytest:

from seleniumbase import BaseCase
BaseCase.main(__name__, __file__)

class ClickButtonTest(BaseCase):
    def test_click_a_button(self):
        self.open("https://www.egle.state.mi.us/RIDE/inventory-of-facilities/facilities")
        self.highlight('button[aria-label="Export Facilities Table results to CSV"]')
        self.click('button[aria-label="Export Facilities Table results to CSV"]')
        self.sleep(5)

The self.highlight() command highlights the button to show it was found. And then it gets clicked.

Answered By: Michael Mintz