无法使用Python Selenium单击ahref链接

2024-06-11 07:10:11 发布

您现在位置:Python中文网/ 问答频道 /正文

这是html代码:

<div id="dcf-page-export-buttons" class="no-print" style="display: block;">
                            <a id="dcf-saveaspdf" href="#" target="_blank" class="k-button">

                                Save as PDF
                            </a>
                            <a id="dcf-saveaspng" href="#" target="_blank" class="k-button">

                                Save as Image
                            </a>
                                                  <a id="dcf-printPdf" class="k-button" href="#">

                                Print
                            </a>
                        <a id="dcf-btnClose" class="k-button" href="#">

                            Close
                        </a>
                   </div>

我想点击打印href,但没有点击。这是我的密码:

exportLink = driver.find_element_by_link_text("Export")
exportLink.click()

print = driver.find_element_by_id("dcf-printPdf")
print.click()

在按id查找要打印的元素之前,我单击了Export href,它打开了一个新选项卡,在打开新选项卡之后,我试图单击print,但出现了一个错误。这就是错误:

selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable

如果我在某个地方出错或者html中有问题,请告诉我


问题的第一部分已经回答。这是第二部分:

单击此打印按钮时: enter image description here

这个窗口打开了。它本身不是一个新选项卡,只是一个新窗口。在该窗口中,我想单击保存按钮。有办法做到这一点吗?这是视图的外观:

enter image description here

这是html代码

<cr-button class="action-button" aria-disabled="false" role="button" tabindex="0">
    Save
  </cr-button>

这是我到目前为止的代码:

exportLink = driver.find_element_by_link_text("Export")
exportLink.click()

driver.switch_to.window(driver.window_handles[1])
driver.execute_script("document.getElementById('dcf-user-info').style.display = 'none';")

time.sleep(1)
print = driver.find_element_by_link_text("Print")
print.click()

这是错误日志的剪报。我添加了剪报,因为我不确定错误

enter image description here

错误的小延续:

enter image description here


Tags: 代码idbyhtmldriver错误buttonelement
2条回答

您需要先切换到“新建”选项卡,然后可以使用您一直尝试的Id单击“打印”

切换到新窗口,如下所示:

driver.switch_to.window(driver.window_handles[1])

从错误中可以看出,您试图访问的元素不可交互。
因此,问题不在于HTML。
我看不到您正在处理的页面,但问题可能是您试图访问的元素不在视图中。
试试这个

from selenium.webdriver.common.action_chains import ActionChains

print = driver.find_element_by_id("dcf-printPdf")

ActionChains(driver).move_to_element(print).click(button).perform()

相关问题 更多 >