Chrome 如何使用python selenium自动执行colab notebook

lyfkaqu1  于 2023-05-11  发布在  Go
关注(0)|答案(1)|浏览(148)

我的代码是:

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

driver = webdriver.Chrome()

url = "https://colab.research.google.com/drive/any colab link=sharing"

driver.get(url)
driver.implicitly_wait(10)

first_run_botton = driver.find_elements(by=By.CSS_SELECTOR, value = r'div > div.cell-execution-indicator > iron-icon')[0]

print(first_run_botton)

first_run_botton.click()
driver.implicitly_wait(10)
error is Exception has occurred: IndexError
list index out of range
  File "C:\Users\Administrator\Desktop\python projects\python yt_video auto\automate colab.py", line 14, in <module>
    first_run_botton = driver.find_elements(by=By.CSS_SELECTOR, value = r'div > div.cell-execution-indicator > iron-icon')[0]
                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^
IndexError: list index out of range

所有运行按钮都有相同的css选择器和xpath,css选择器和xpath是从chrome复制的,请帮助!!

wz3gfoph

wz3gfoph1#

我想你是想点击运行单元格按钮来获取代码片段,如果你看一下colab html,你可以清楚地看到它是一个影子DOM的一部分,这就是为什么你不能直接在Selenium中访问它。如果有任何元素在#shadow-root(open)下,我们需要首先找到它的父元素,然后获取shadowroot,然后可以访问shadowroot中的元素

下面的解决方案应该工作,我已经测试了他们对样本colab链接下面

1如果您使用的是Selenium > 4.1,您可以通过sleenium本身访问shadowRoot,因为它从版本> 4.1支持它,这应该点击运行按钮的第一个片段,您可以根据您的链接更新定位器

driver.get("https://colab.research.google.com/notebooks/snippets/importing_libraries.ipynb")

driver.implicitly_wait(20)
# Find Shadow Element First
shadow = driver.find_element(By.XPATH, '(//colab-run-button[@aria-label="Run cell"])[2]').shadow_root

runButton = shadow.find_element(By.CSS_SELECTOR, 'div[class="cell-execution-indicator"] > iron-icon')
runButton.click()

如果你使用 selenium 3.版本,然后我们需要使用javascript首先得到的shadowroot,然后遍历它得到运行按钮

driver.get("https://colab.research.google.com/notebooks/snippets/importing_libraries.ipynb")

driver.implicitly_wait(20)

# Find Shadow Element First
shadow = driver.find_element(By.XPATH, '(//colab-run-button[@aria-label="Run cell"])[2]')

shadow = driver.execute_script('return arguments[0].shadowRoot;', shadow)

runButton = shadow.find_element(By.CSS_SELECTOR, 'div[class="cell-execution-indicator"] > iron-icon')
runButton.click()

阅读本文以了解有关Shadow DOM的更多信息

相关问题