Selenium无法通过XPath找到元素?

huangapple go评论75阅读模式
英文:

Selenium Can't Find element by Xpath?

问题

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 the image below: Selenium无法通过XPath找到元素?

Before posting, I've referenced the following Questions:

  1. https://stackoverflow.com/questions/72003047/clicking-a-button-with-selenium-button
  2. https://stackoverflow.com/questions/8871654/how-to-press-click-the-button-using-selenium-if-the-button-does-not-have-the-id
  3. https://stackoverflow.com/questions/72754651/attributeerror-webdriver-object-has-no-attribute-find-element-by-xpath

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

英文:

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: Selenium无法通过XPath找到元素?
Before posting I've referenced the following Questions:

  1. https://stackoverflow.com/questions/72003047/clicking-a-button-with-selenium-button
  2. https://stackoverflow.com/questions/8871654/how-to-press-click-the-button-using-selenium-if-the-button-does-not-have-the-id
  3. https://stackoverflow.com/questions/72754651/attributeerror-webdriver-object-has-no-attribute-find-element-by-xpath

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

答案1

得分: 1

我能够使用SeleniumBase点击该按钮。

pip install seleniumbase,保存以下脚本到文件中,然后使用pythonpytest运行:

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)

self.highlight()命令会突出显示按钮以显示已找到它。然后它被点击。

英文:

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.

答案2

得分: 1

以下是翻译好的内容:

你可以只使用 Selenium 轻松完成它。

这是如何操作的:

import os
from selenium.webdriver import Chrome, ChromeOptions
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

def download_file(path):

    options = ChromeOptions()
    options.add_argument('--start-maximized')
    prefs = {'download.default_directory': path}
    options.add_experimental_option('prefs', prefs)

    driver = Chrome(options=options)
    driver.get('https://www.egle.state.mi.us/RIDE/inventory-of-facilities/facilities')
    wait = WebDriverWait(driver, 100)

    wait.until(EC.presence_of_all_elements_located((By.TAG_NAME, 'mat-table')))
    driver.execute_script('document.querySelector("button[aria-label=\'Export Facilities Table results to CSV\']").click();')

    while True:
        is_exist = os.path.exists(f"{path}\\Facilities.csv")
        if is_exist:
            print("文件已下载!")
            break

PATH = 'D:\\test'
download_file(PATH)

输出:

文件已下载!

操作步骤:

  1. 由于该网站需要一些时间来加载所需的元素(这里是 导出 按钮)。单击此按钮将下载表格的数据。因此,我们等待确保表格数据已加载。

  2. 现在数据已经加载,只需单击 导出 按钮以下载数据(这里是 Facilities.csv)。

  3. 文件在给定路径下载需要一些时间,因此我们需要等待文件下载完成。为此,我们不断检查文件是否存在于给定路径,并一旦文件存在,就中断循环。

希望这解决了您的问题。

英文:

You can easily do it using Selenium only.

Here's how:

import os
from selenium.webdriver import Chrome, ChromeOptions
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

def download_file(path):

    options = ChromeOptions()
    options.add_argument('--start-maximized')
    prefs = {'download.default_directory': path}
    options.add_experimental_option('prefs', prefs)

    driver = Chrome(options=options)
    driver.get('https://www.egle.state.mi.us/RIDE/inventory-of-facilities/facilities')
    wait = WebDriverWait(driver, 100)

    wait.until(EC.presence_of_all_elements_located((By.TAG_NAME, 'mat-table')))
    driver.execute_script('''document.querySelector("button[aria-label='Export Facilities Table results to CSV']").click();''')

    while True:
        is_exist = os.path.exists(f"{path}\\Facilities.csv")
        if is_exist:
            print(f"The file is downloaded!")
            break

PATH = 'D:\\test'
download_file(PATH)

output:

The file is downloaded!

steps to follow:

  1. As the site takes some time to load the desired element (here, the Export button). And clicking on this button downloads the data of the table. Therefore we wait to make sure that the table data is already loaded.

  2. Now that the data is already loaded, simply click on the Export button to download the data (here Facilities.csv).

  3. It takes some time for the file to get downloaded at the given path, so we need to wait until the file download is completed. To do this, we keep checking if the file is present at the given path, and once the file is there, we break the loop.

I hope it solves your problem.

huangapple
  • 本文由 发表于 2023年6月9日 08:16:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76436438.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定