正在使用 Selenium 下载 google 文档

Downloading google doc with Selenium

我正在尝试使用 Python 中的 Selenium 下载 pdf 格式的 google 文档。不幸的是,我的 html 知识非常少,因此我不知道 html 我需要什么点击文件然后下载为 pdf。我意识到我可以使用 Web 开发人员工具来获取 html 但这对我来说效果不是很好。

这是我目前尝试过的方法:

from selenium import webdriver 

url = ' https://docs.google.com/document/d/1Y1n-RR5j_FQ9WFMG8E_ajO0OpWLNANRu4lQCxTw9T5g/edit?pli=1' 

browser = webdriver.Firefox()
browser.get(url)

如有任何帮助,我们将不胜感激;谢谢!

正如您在评论中提到的,Google Drive 不喜欢被抓取。

drive 命令看起来是完成此类工作的正确工具。 - 它会做你想做的事,但不是你想做的事。根据文档(即我还没有测试过),这个命令看起来会下载你的文件:

drive pull --export docx --id 1Y1n-RR5j_FQ9WFMG8E_ajO0OpWLNANRu4lQCxTw9T5g

(此外,一般来说,我发现使用 Selenium 最简单的方法是使用 Selenium IDE 告诉 Selenium 你想做什么,然后通过转到 File > Export Test Case As... > Python 2 / unittest / Web Driver.)

希望对您有所帮助。

我有一个有效的解决方案,我不知道 google 是否会更新以缓解这种情况。现在这是在 c# 中,但 selenium 功能基本相同。 显示所有菜单项,但下载为菜单和 return 下载为网络元素除外。使用 selenium 单击它,然后 select 格式和 return webelement 也可以单击。我无法仅使用 javascript 进行点击,我无法弄清楚他们是如何触发它的,但是使用 selenium 驱动程序点击它工作得很好。

使大部分菜单可见并return下载为网络元素。

  document.querySelector(`#docs-file-menu`).className = 'menu-button goog-control goog- 
  inline-block goog-control-open docs-menu-button-open-below';
  document.querySelector(`#docs-file-menu`).setAttribute('aria-expanded', 'true');
  document.querySelectorAll(`.goog-menu:not(.goog-menu-noaccel)`)[0].className = 'goog-menu goog-menu-vertical docs-material docs-menu-hide-mnemonics docs-menu-attached-button-above';
  document.querySelectorAll(`.goog-menu:not(.goog-menu-noaccel)`)[0].setAttribute('style', 'user-select: none; visibility: visible; left: 64px; top: 64px;');
  // download as
  // 2 parents above 
  document.querySelector(`[aria-label='Download as d']`).parentElement.parentElement.className = 'goog-menuitem apps-menuitem goog-submenu goog-submenu-open goog-menuitem-highlight'
  return document.querySelector(`[aria-label='Download as d']`).parentElement.parentElement;

点击下载为 btn:

IWebElement btn = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript(btnClickJs);
btn.Click();

Select格式:

var formatCss = document.querySelectorAll(`.goog-menu.goog-menu-noaccel`)[6].querySelectorAll(`.goog-menuitem.apps-menuitem`)
                            var format = 'injectformathere' ? 'injectformathere' : '.html'

for (let i = 0; i < formatCss.length; i++) {
   if(formatCss[i].innerText.indexOf(format)!= -1)
       return formatCss[i]    
   }
return null

点击格式:

btn = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript(btnClickJs);
if (btn != null)
  btn.Click();