我需要获取按钮的元素,以使用 selenium 将 MetaMask 钱包连接到多边形网桥。
我需要找到的按钮: 但据我了解,该按钮隐藏在 html 页面的影子根目录中。
如果我通过右键单击并“检查”找到按钮的 HTML 代码,我可以尝试复制它的 X 路径。
当我粘贴它时:/button
这是行不通的:
metamask = wait.until(EC.element_to_be_clickable((By.XPATH, '/button')))
metamask.click()
导致错误。这些错误的文本每次都是相同的,所以我将其粘贴在最后。
如果我尝试右键单击、“检查”并复制 CSS 选择器,它也不起作用。
复制的 CSS 选择器是:button:nth-child(1)
我无法使用此按钮。
现在,当我尝试通过 CSS-Selector 或 X-Path 查找按钮时出现的错误文本:
Traceback (most recent call last):
File "C:\Users\childoflogos\Desktop\selenium_airdrop_hunter\main.py", line 126, in <module>
metamask = wait.until(EC.element_to_be_clickable((By.XPATH, '/button')))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\childoflogos\Desktop\selenium_airdrop_hunter\venv\Lib\site-packages\selenium\webdriver\support\wait.py", line 95, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
Stacktrace:
Backtrace:
GetHandleVerifier [0x00B9A813+48355]
(No symbol) [0x00B2C4B1]
(No symbol) [0x00A35358]
(No symbol) [0x00A609A5]
(No symbol) [0x00A60B3B]
(No symbol) [0x00A8E232]
(No symbol) [0x00A7A784]
(No symbol) [0x00A8C922]
(No symbol) [0x00A7A536]
(No symbol) [0x00A582DC]
(No symbol) [0x00A593DD]
GetHandleVerifier [0x00DFAABD+2539405]
GetHandleVerifier [0x00E3A78F+2800735]
GetHandleVerifier [0x00E3456C+2775612]
GetHandleVerifier [0x00C251E0+616112]
(No symbol) [0x00B35F8C]
(No symbol) [0x00B32328]
(No symbol) [0x00B3240B]
(No symbol) [0x00B24FF7]
BaseThreadInitThunk [0x76A100C9+25]
RtlGetAppContainerNamedObjectPath [0x77D77B4E+286]
RtlGetAppContainerNamedObjectPath [0x77D77B1E+238]
selenium 无法找到并单击元素时的常见错误
Button element in HTML code of the page (better try to locate the element in html code yourself)
如何使用 selenium 找到并单击此按钮?
更新: 我找到了有关如何在影子根中定位元素的信息:
shadow_element = driver.execute_script("return document.querySelector('w3m-modal').shadowRoot.querySelector('div').querySelector('div')")
但我仍然无法创建通往目标按钮的路径 上面的代码到达了正确的影子根内部的 div 之一,但在以下 html 注释后无法捕获任何元素:
<!--?lit$702571791$-->
我如何继续并掌握上面评论后面的元素?
最佳答案
<button>
元素在多个 #shadow-root (open) 内
解决方案
要单击带有文本 MetaMask 的按钮,您需要引入 WebDriverWait对于 element_to_be_clickable()您可以使用以下 locator strategy :
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((driver.execute_script("return document.querySelector('w3m-connect-wallet-view').shadowRoot.querySelector('w3m-desktop-wallet-selection').shadowRoot.querySelector('w3m-wallet-button').shadowRoot.querySelector('button > div > w3m-text.w3m-sublabel')")))).click()
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
关于python - Selenium : how to get element in shadow root of html page code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76658230/