如何使用带有 aria-label 的 selenium 单击 python 中的按钮

How to click on a button in python using selenium with aria-label

我正在尝试查找并单击 iframe 上的 关闭 按钮。

<modal-container class="modal fade show" role="dialog" tabindex="-1" style="display: block;" aria-modal="true"><div role="document" class="modal-dialog modal-xl"><div class="modal-content"><div _ngcontent-gtk-c9="" class="modal-header card-header modal-header-news-expanded"><h4 _ngcontent-gtk-c9="" align="center" class="modal-title col-11 text-center">Article Title PDF </h4><button _ngcontent-gtk-c9="" aria-label="Close" class="close close_white_color" type="button"><span _ngcontent-gtk-c9="" aria-hidden="true">×</span></button></div><br _ngcontent-gtk-c9=""><div _ngcontent-gtk-c9="" class="container-fluid"><!----><div _ngcontent-gtk-c9="" class="row"><!----><div _ngcontent-gtk-c9="" class="col-md-12 ng-star-inserted"><!----><iframe _ngcontent-gtk-c9="" id="pdf_iframe_outside_modal" src="link.com" class="ng-star-inserted" cd_frame_id_="337af673cf64fd1888fcd2afe645984c"></iframe><!----></div></div><!----></div></div></div></modal-container>

我试过以下方法:

尝试 1:

close = driver.find_element_by_xpath("//button[@aria-label=Close']").click()

尝试2:

close = driver.find_element_by_xpath("//button[@class='close close_white_color']").click()

尝试 3:

close = driver.find_element_by_xpath("//button[contains(@class,\"close close_white_color\")]").click()

给出以下错误

错误 1:

NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//button[@aria-label='Close']"}

错误2:

NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//button[@class='close close_white_color']"}

错误 3:

NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//button[contains(@class,"close close_white_color")]"}

我可以与 iframe 交互,但找不到此按钮。如有任何建议,我们将不胜感激

这里有几件事:

  • 该元素不在
  • 没有 returns 任何东西。

解决方案

所需元素在 Modal Dialog Box, to click on the clickable element you need to induce WebDriverWait for the and you can use either of the following :

  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.close.close_white_color[aria-label='Close'] > span"))).click()
    
  • 使用 XPATH:

    //button[@class='close close_white_color' and @aria-label='Close']/span
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC