我正在try 单击一个按钮,以自动从this site中导出CSV文件.我try 通过按钮名称和XPath查找元素,但引发了"NoSuchElement"异常.我try 了WebdriverWait和Time的变体.睡眠以确保按钮加载,并使用XPath查找器扩展来获得正确的XPath.

代码如下:

#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]/facilitielayui-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'

*刚接触Selify,不太精通HTML.任何洞察力都是非常值得赞赏的.

推荐答案

我用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()命令高亮显示该按钮,以显示已找到该按钮.然后它被点击.

Python相关问答推荐

GL pygame无法让缓冲区与vertextPointer和colorPointer一起可靠地工作

通过优化空间在Python中的饼图中添加标签

pandas DataFrame GroupBy.diff函数的意外输出

Python json.转储包含一些UTF-8字符的二元组,要么失败,要么转换它们.我希望编码字符按原样保留

Pandas - groupby字符串字段并按时间范围 Select

如何在python polars中停止otherate(),当使用when()表达式时?

如何在Python脚本中附加一个Google tab(已经打开)

如何将一个动态分配的C数组转换为Numpy数组,并在C扩展模块中返回给Python

如何设置视频语言时上传到YouTube与Python API客户端

pandas:排序多级列

如何在UserSerializer中添加显式字段?

为什么Django管理页面和我的页面的其他CSS文件和图片都找不到?'

python中csv. Dictreader. fieldname的类型是什么?'

ModuleNotFoundError:没有模块名为x时try 运行我的代码''

Polars Group by描述扩展

不允许 Select 北极滚动?

按条件添加小计列

为什么后跟inplace方法的`.rename(Columns={';b';:';b';},Copy=False)`没有更新原始数据帧?

Django.core.exceptions.SynchronousOnlyOperation您不能从异步上下文中调用它-请使用线程或SYNC_TO_ASYNC

有什么方法可以在不对多索引DataFrame的列进行排序的情况下避免词法排序警告吗?