【问题标题】:How can I send an email from Gmail with Python + Selenium?如何使用 Python + Selenium 从 Gmail 发送电子邮件?
【发布时间】:2021-12-08 10:52:33
【问题描述】:

我正在尝试使用 Selenium 从 Gmail 的网络界面使用 Python 发送一封电子邮件,但我在选择撰写部分时遇到了困难。

这是我的代码:

from selenium import webdriver
import time

driver = webdriver.Chrome('C:\chromedriver.exe')


driver.get('https://www.gmail.com/')


driver.implicitly_wait(5)

loginBox = driver.find_element_by_xpath('//*[@id ="identifierId"]')
loginBox.send_keys('xxxxxxxxxxxxxxxxx')

nextButton = driver.find_elements_by_xpath('//*[@id ="identifierNext"]')
nextButton[0].click()

passWordBox = driver.find_element_by_xpath('//*[@id ="password"]/div[1]/div / div[1]/input')
passWordBox.send_keys('xxxxxxxxxxxx')

nextButton = driver.find_elements_by_xpath('//*[@id ="passwordNext"]')
nextButton[0].click()

time.sleep(2)

#compose = driver.find_element_by_xpath('/html/body/div[7]/div[3]/div/div[2]/div[1]/div[1]/div[1]/div[2]/div/div/div/div[1]/div/div')                         
#compose.click()

driver.get('https://mail.google.com/mail/u/0/#inbox?compose=new')

time.sleep(2)


compose_button_xpath="/html/body/div[7]/div[3]/div/div[2]/div[1]/div[1]/div[1]/div[2]/div/div/div/div[1]/div/div"
#driver.find_element_by_xpath(compose_button_xpath).click()
driver.find_element_by_xpath("//textarea[@name='to']").send_keys("abc@gmail.com")
driver.find_element_by_xpath("//*[@id=':12s']").send_keys("Content")
driver.find_element_by_xpath("//*[@id=':11d']").click()

你能帮帮我吗?我该如何解决这个问题?

【问题讨论】:

  • 您是否考虑过使用例如smtplib 而不是网络自动化?与使用 selenium 相比,这将是一种更清洁、更简单的电子邮件发送方式。尝试谷歌搜索“使用 python smtplib 发送 gmail”或类似内容
  • 是的,我已经考虑过了,但我想做的是通过 selenium 自动化它。谢谢
  • 好的,我现在没有时间研究细节,但猜测是带有消息等的弹出窗口位于另一个窗口句柄内(例如在 iframe 中),这意味着您需要切换上下文以到达它。在这个答案中尝试类似的东西:stackoverflow.com/questions/66568508/…
  • 不,我想我想用 selenium 自动化 gmail 是很清楚和准时的

标签: python selenium gmail


【解决方案1】:

哇,Gmail 的 HTML 真是一团糟。

无论如何,我已经用这个 xPath 找到了 Compose 按钮​​:

'//*[contains(@class, "T-I") and contains(@class, "L3") and contains(@class, "T-I-KE")]'

【讨论】:

  • 我明白了:selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素
  • driver.find_element_by_xpath('//*[contains(@class, "T-I") and contains(@class, "L3") and contains(@class, "T-I-KE")]' ).click()
  • 我看过这个视频,但它对我不起作用:/ youtube.com/watch?v=vkRpOIuvwkg&ab_channel=DeepDataScience,是的,Gmail 的 HTML 是一团糟
  • 当你检查按钮时,它有什么类?
  • 可能是动态的:(
猜你喜欢
  • 1970-01-01
  • 2020-07-13
  • 2020-07-12
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
  • 2016-03-22
  • 1970-01-01
  • 2013-10-17
相关资源
最近更新 更多