1. 程式人生 > >Python 編程快速上手 讓繁瑣工作自動化-第十一章實踐項目 11.11.1命令行郵件程序

Python 編程快速上手 讓繁瑣工作自動化-第十一章實踐項目 11.11.1命令行郵件程序

tabindex 程序 scroll browser dex from 主題 代碼 contain

11.11.1 命令行郵件程序

  1. 編寫一個程序,通過命令行接受電子郵件地址和文本字符串。然後利用selenium
    登錄到你的郵件賬號,將該字符串作為郵件,發送到提供的地址(你也許希望為這
    個程序建立一個獨立的郵件賬號)。
    這是為程序添加通知功能的一種好方法。你也可以編寫類似的程序,從
    Facebook 或Twitter 賬號發送消息。
    這個項目弄了好幾天,頭都快炸了,終於弄好了
    代碼如下:
    #!/usr/bin/env python
    #encoding:utf-8

‘‘‘@author:Kevin
br/>@author:Kevin
br/>@file:eMail.py
br/>@desc:
‘‘‘
from selenium import webdriver

from selenium.webdriver.common.keys import Keys
import time

url=‘https://www.yeah.net‘

browser = webdriver.Chrome() #打開瀏覽器

browser.get(url)

time.sleep(2)
#切換iframe
#browser.switch_to.frame(‘x-URS-iframe‘) #報錯
#上面那條語句中,iframe的切換是默認支持id和name的方法的,
#當然實際情況中會遇到沒有id屬性和name屬性為空的情況,
#這時候就需要先定位iframe
iframe=browser.find_element_by_tag_name("iframe")

browser.switch_to.frame(iframe)

#查找email賬號填寫框
emailElem = browser.find_element_by_name(‘email‘)
emailElem.send_keys(‘not-a-real-email-address‘) # 調用send_keys()方法填寫表單

#查找密碼填寫框
passwordElem = browser.find_element_by_name(‘password‘)
passwordElem.send_keys(‘****‘)

#查找登錄按鈕
loginElem = browser.find_element_by_id(‘dologin‘)

loginElem.click() #模擬鼠標點擊登錄
time.sleep(2) #
browser.switch_to.default_content()

#查找寫信按鈕
writeElem=browser.find_element_by_id(‘_mail_component_23_23‘)
writeElem.click() #模擬鼠標點擊登錄
time.sleep(2)

#填寫收件人地址
recipientElem=browser.find_element_by_class_name(‘nui-editableAddr-ipt‘)
recipientElem.send_keys(‘[email protected]‘)

#填寫郵件主題
subjectElem=browser.find_element_by_xpath("//*[@class=‘nui-ipt-input‘and @type = ‘text‘ and @tabindex = ‘1‘]")
subjectElem.send_keys(‘Hello!‘)

#填寫郵件內容mainbodyFrame=browser.find_element_by_xpath("//iframe[contains(@class,‘APP-editor-iframe‘)]")
br/>mainbodyFrame=browser.find_element_by_xpath("//iframe[contains(@class,‘APP-editor-iframe‘)]")
mainbodyElem=browser.find_element_by_class_name(‘nui-scroll‘)
mainbodyElem.send_keys(‘Hello!\nWorld!‘)
browser.switch_to.default_content()

#點擊發送按鈕
sendElem=browser.find_elements_by_class_name("nui-btn-text")[2]
sendElem.click()
time.sleep(5)
browser.quit()

Python 編程快速上手 讓繁瑣工作自動化-第十一章實踐項目 11.11.1命令行郵件程序