如何使用Selenium发送Google文档中的密钥

时间:2018-10-11 18:19:55

标签: python selenium webdriver

我正在尝试使用Selenium自动创建Google文档并向其中添加随机文本。我已经在该程序中创建了一个名为doccontent的列表,该列表可从该列表中提取出来,以输入Google文档的正文中,但似乎无法正常工作。这是我的代码的一部分:

import random
from selenium import webdriver
import time

driver = webdriver.Chrome()

#creating doc
driver.get("https://docs.google.com/document/u/0/")
time.sleep(random.randint(1,2))
newdoc = driver.find_element_by_xpath('//*[@id=":1d"]/div[1]')
newdoc.click()
time.sleep(2)
#adding random doc name

rename = driver.find_element_by_class_name('docs-title-input')
rename.click()
docname = "test" + str(random.randint(1,600))
rename.send_keys(docname)

body = driver.find_element_by_class_name('kix-lineview')
time.sleep(1)
docwords = random.choice(doccontent)
body.send_keys(docwords)

它返回错误:

  

selenium.common.exceptions.WebDriverException:消息:未知错误:无法聚焦元素     (会议信息:chrome = 69.0.3497.100)     (驱动程序信息:chromedriver = 2.42.591088(7b2b2dca23cca0862f674758c9a3933e685c27d5),platform = Windows NT 10.0.17134 x86_64)

编辑:

只需将其更改为:

#creating doc
driver.get("https://docs.google.com/document/u/0/")
time.sleep(random.randint(1,2))
newdoc = driver.find_element_by_xpath('//*[@id=":1d"]/div[1]')
newdoc.click()
time.sleep(2)
#adding random doc name
rename = driver.find_element_by_class_name('docs-title-input')
rename.click()
docname = "test" + str(random.randint(1,600))
rename.send_keys(docname)

body = driver.find_element_by_class_name('kix-page-column')
time.sleep(1)
docwords = random.choice(doccontent)
actions = ActionChains(driver)
actions.send_keys(Keys.TAB * 15)
actions.perform()
time.sleep(1)
body.send_keys(docwords)

这是尝试进入文档的选项卡,但仍然会显示错误:

  

selenium.common.exceptions.WebDriverException:消息:未知错误:无法聚焦元素     (会议信息:chrome = 69.0.3497.100)     (驱动程序信息:chromedriver = 2.42.591088(7b2b2dca23cca0862f674758c9a3933e685c27d5),platform = Windows NT 10.0.17134 x86_64)

2 个答案:

答案 0 :(得分:0)

我也有同样的情况。这就是我能够获取文本到Google文档的方式:

doc_text = driver.find_element_by_xpath('//body')
doc_text.send_keys('This should be now in the Google Doc's Body')

编辑: 经过一些测试之后,您应该确定要花一些时间直到页面完全加载,然后在之前插入标题文本

答案 1 :(得分:0)

这是我用来向Google文档发送文本的代码:

#Import ActionChains
from selenium.webdriver.common.action_chains import ActionChains

#Find element on page(Use (Shift + Right Click) to inspect element)
doc = driver.find_element_by_xpath("insert xpath here")

Wait for a Little Bit
driver.implicitly_wait(10)

#Move to element, click it, and then send text to where your cursor is
ActionChains(driver).move_to_element(doc).click(doc).send_keys("hi").perform()

上方的ActionChains行允许我们执行此操作,因此请充分利用