如何使用Selenium点击Google Slides中Linked Objects下的Update all按钮
用Selenium操作Google Slides批量更新所有关联对象
Google Slides在「工具>>Linked Objects」菜单下设有名为「Update all」的选项,可更新演示文稿内的所有元素。类似功能也可通过Google App Scripts实现,但仅支持更新图表,无法更新表格,因此该方案及同类变通方法均无法满足使用需求。
此前使用Selenium实现其他网站的任务自动化时,因为Google Slides的元素值为动态生成,使用如下代码无法成功操作:
tool_menu = wd.find_element(By.CSS_SELECTOR, 'menu.tool') tool_menu.click()
经过多轮调试,最终可正常运行的代码如下(适配Google Colab运行环境):
# Google Colab环境初始化配置 !pip install selenium !apt-get update !apt install chromium-chromedriver !cp /usr/lib/chromium-browser/chromedriver /usr/bin import sys sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver') from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') wd = webdriver.Chrome('chromedriver',chrome_options=chrome_options) from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options import time # 替换为目标演示文稿的链接 wd.get("https://docs.google.com/presentation/d/[id]/") from IPython.core.display import Image, display file_name = "part.png" wd.set_window_size(1920,1080) wd.get_screenshot_as_file(file_name) display(Image(file_name)) # 打开工具菜单 wd.find_element(By.ID,'docs-tools-menu').click() time.sleep(1) # 生产环境建议替换为显式等待 wd.get_screenshot_as_file(file_name) display(Image(file_name)) menus = wd.find_elements(By.XPATH, '//div[@role="menu"]') menu = None # 遍历找到当前可见的菜单元素 for m in menus: if m.is_displayed(): menu = m break assert menu # 选择Linked Objects菜单项,可根据界面语言修改menu_label取值 menu_label = "Linked objects" item = menu.find_element(By.XPATH,'//span[contains(@aria-label, "%s")]' % menu_label) item.click() time.sleep(3) # 生产环境建议替换为显式等待 wd.get_screenshot_as_file(file_name) display(Image(file_name)) # 点击刷新按钮,可根据界面语言修改refresh_label取值 refresh_label = "Refresh" refresh_btn = wd.find_element(By.XPATH,'//div[contains(@aria-label, "%s")]' % refresh_label) refresh_btn.click() time.sleep(3) wd.get_screenshot_as_file(file_name) display(Image(file_name)) # 点击全部更新按钮 update_all_btn = wd.find_element(By.XPATH,'//div[contains(@class, "update-all-button")]') update_all_btn.click()
内容的提问来源于stack exchange,提问作者user3347814
相关产品推荐
相关产品推荐

