赞
踩
基于Selenium+Python的自动化测试,实现qq邮箱登录并发送邮件。
①下载网址:https://www.anaconda.com/products/individual
②配置环境变量:安装过程中记得勾选Add PATH选项 。



查看谷歌浏览器版本

根据对应的版本选择相匹配的webdriver,网址为:http://chromedriver.storage.googleapis.com/index.html
运行conda env list

可以看到项目在anaconda环境中的位置,找到它。
将下载好解压出来的chromedriver.exe拷贝到上一步找到的文件夹中,即anaconda环境中的项目目录文件夹:

from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
# 使用headless无界面浏览器模式
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
# 启动浏览器,获取网页源代码
browser = webdriver.Chrome(chrome_options=chrome_options)
mainUrl = "https://www.taobao.com/"
browser.get(mainUrl)
print(f"browser text = {browser.page_source}")
browser.quit()

经过以上步骤,测试环境基本配置完成,接下来进行测试实验。
运行以下代码:
from selenium import webdriver
import time
chrome = webdriver.Chrome()
chrome.get('https://mail.qq.com/')
或者直接手动打开浏览器并输入qq邮箱地址。
浏览器打开QQ邮箱登录网址:QQ邮箱登录地址为:https://mail.qq.com/
审查元素:F12并选中输入框

但是使用指导书中代码,提示:

写法更新了,所以根据提示更新代码。
并且现在的qq邮箱是优先显示扫码登录,所以还需要一步点击操作将登录组件改为账号密码登录:

登录代码(完整):
from selenium import webdriver import time from selenium.webdriver.common.by import By chrome = webdriver.Chrome() chrome.get('https://mail.qq.com/') chrome.switch_to.frame("login_frame") chrome.find_element(by=By.ID, value='switcher_plogin').click() #账户 chrome.find_element(by=By.ID, value='u').send_keys("**********") #密码 chrome.find_element(by=By.ID, value='p').send_keys("**********") chrome.find_element(by=By.ID, value='login_button').click()
运行上述代码,可以成功登录自动邮箱了,注意将账户密码改为自己的。

审查元素,写信操作:

进入写信页面,审查表单元素:

可以看到各输入框id分别为to、subject,正文部分,值得注意!正文输入部分位于另一个iframe中!
所以要注意切换iframe后,再进行对应下面元素的操作。
本项目完整代码:
from selenium import webdriver import time from selenium.webdriver.common.by import By chrome = webdriver.Chrome() chrome.get('https://mail.qq.com/') chrome.switch_to.frame("login_frame") chrome.find_element(by=By.ID, value='switcher_plogin').click() #自己的账户信息 chrome.find_element(by=By.ID, value='u').send_keys("********") chrome.find_element(by=By.ID, value='p').send_keys("********") chrome.find_element(by=By.ID, value='login_button').click() # 写信操作 chrome.switch_to.default_content() #等待一秒 time.sleep(1) # 定位写信按钮 chrome.find_element(by=By.ID, value='composebtn').click() # 切换到mainFrame chrome.switch_to.frame('mainFrame') time.sleep(1) # 定位收件人(邮箱),并输入 chrome.find_element(By.XPATH, value="//*[@id='toAreaCtrl']/div[2]/input").send_keys("********") # 定位主题,并输入 chrome.find_element(By.ID, value='subject').send_keys("主题") # 定位邮件正文,先进入到iframe chrome.switch_to.frame(chrome.find_element(By.CLASS_NAME, value="qmEditorIfrmEditArea")) # 必须先点击正文,再send_keys chrome.find_element(By.XPATH, value='/html/body').click() chrome.find_element(By.XPATH, value='/html/body').send_keys("Hello World!") # 返回到mainframe chrome.switch_to.parent_frame() # 定位发送按钮 chrome.find_element(By.XPATH, value='//*[@name="sendbtn"]').click()

成功发送邮件,实验完成。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。