天天看點

Python 3 + Selenium 126郵箱自動發送郵件執行個體

Python 3 + Selenium 126郵箱自動發送郵件執行個體

因為版本問題,是以一設定隐形等待就報錯,處理半天解決不了,幹脆就用強制等待了。

以下是源代碼,有需要的可以參考下。

from selenium import webdriver
import time

#config===================================================================
account = 'account' #賬号
password = 'password' #密碼
address = '[email protected]' #寄給誰
title = 'Test for auto send' #标題
text = '這裡是正文' #正文
document = 'D:\\Users\\hli7\\Desktop\\2.py' #附件
#=========================================================================
driver = webdriver.Firefox() #使用火狐
driver.get('https://www.126.com') #通路126
time.sleep(2)
driver.switch_to.frame(driver.find_element_by_tag_name("iframe")) #登入框是iframe嵌入在前端裡的,得先切換才能取到iframe裡的元素
driver.find_element_by_name("email").clear() #清空賬号欄
driver.find_element_by_name("email").send_keys("account") #輸入賬号
driver.find_element_by_name("password").clear()
driver.find_element_by_name("password").send_keys("password")
driver.find_element_by_id("dologin").click() #點選登入

driver.switch_to.default_content()
time.sleep(3)
driver.find_element_by_xpath("//span[text()='寫 信']").click()
time.sleep(2)
driver.switch_to.default_content()
driver.find_element_by_xpath("//*[@title='發給多人時位址請以分号隔開']").click()
driver.find_element_by_xpath("//*[@title='發給多人時位址請以分号隔開']").send_keys(address)
time.sleep(2)

#這裡注意下,使用的是elements,并找的是[2]。
driver.find_elements_by_class_name("nui-ipt-input")[2].clear()
driver.find_elements_by_class_name("nui-ipt-input")[2].send_keys(title)
driver.find_element_by_xpath('//input[@type="file"]').send_keys(document)

zhengwenf = driver.find_element_by_class_name("APP-editor-iframe")
driver.switch_to.frame(zhengwenf)
#輸入正文
driver.find_element_by_xpath('//body[@class="nui-scroll"]').send_keys(text)
driver.switch_to_default_content()
#點選發送
time.sleep(3)
driver.find_element_by_xpath("//*[text()='發送']").click()
driver.find_elements_by_class_name("nui-btn-text")[-2].click()
time.sleep(5)
driver.switch_to.default_content()
#設定了一個斷言,看到發送成功這個字段表示發送成功。但好像沒設定好,print不出來。
success = driver.find_element_by_xpath("//*[text()='發送成功']").text
if (success == '發送成功'):
    print('ok')
driver.quit()