1

我正在尝试单击一个看起来像存在于阴影根中的按钮。下面是我试图点击的图片:

在此处输入图像描述

当我尝试单击其上方的元素时,收到元素不可交互的错误。

搜索 amazon prime music 上的任何歌曲以自行完成。

方法一

song_result = driver.find_element(By.XPATH,"/html/body/div/music-app/div[4]/div/div/div/music-container/music-container[2]/div/music-shoveler")
song = song_result.find_element(By.TAG_NAME,"music-horizontal-item")
a = song.find_elements(By.TAG_NAME,"music-button")
a[1].click()

方法二

driver.find_element(By.XPATH,"/html/body/div/music-app/div[4]/div/div/div/music-container/music-container[2]/div/music-shoveler/music-horizontal-item[1]/music-button[2]//button").click()
        

其实顺序是这样的:

<music-horizontal-item>
    <music-button>
        #shadowRoot
        <button>
    <music-button>
        #shadowRoot
        <button>This button I need to click

所以我按照你的建议使用了这个

song_result = driver.find_element(By.XPATH,"/html/body/div/music-app/div[4]/div/div/div/music-container/music-container[2]/div/music-shoveler")
song = song_result.find_element(By.TAG_NAME,"music-horizontal-item")
a = song.find_elements(By.TAG_NAME,"music-button")
song_root = driver.execute_script("return arguments[0].shadowRoot",a[1])
song_root.find_element(By.TAG_NAME,"button").click()a

仍然收到此错误:

Message: element not interactable
4

1 回答 1

1

首先,您必须使用 js 选择 shadow dom 作为元素,然后使用 seleniumfind函数在其中搜索:

方法1

song = song_result.find_element(By.TAG_NAME,"music-button")
song_root = expand_element(song)
a = song_root.find_elements(By.TAG_NAME,"button")
a[1].click()

然后编写expand_element函数在元素上执行js脚本并获取shadowRoot更多

def expand_element(element):
    return driver.execute_script("return arguments[0].shadowRoot",element)

方法2(直接):

song_root = driver.execute_script("return document.querySelector('music-button').shadowRoot")
a = song_root.find_elements(By.TAG_NAME,"button")
a[1].click()

我看不到父元素,但所说的是shadow dom中的“查找结构”

music_h_i = driver.find_element_by_xpath("//music-horizontal-item")
music_h_i_expanded = expand_element(music_h_i)
music_button = music_h_i_expanded.find_elements(By.TAG_NAME,"music-button")
music_button_expanded = expand_element(music_button)
music_button.click() # or music_button_expanded.click()

不需要使用 xpath from /html/body/,xpath 有很好的搜索功能

于 2021-10-15T13:42:05.327 回答