使用python+selenium 实现chrome免登录QQ邮箱和完成发送信件
第一次使用csdn 直接贴代码吧:
"""
改进qq邮箱的免登录以及发送邮件
使用webdriverwait()登录的方法
实现chrome免登录
"""
import time
from selenium.webdriver.support.wait import WebDriverWait
from selenium import webdriver
# import …..as….进行重命名
from selenium.webdriver.support import expected_conditions as EC
# 设置chrome启动参数
options = webdriver.ChromeOptions()
# 设置浏览器驱动提示信息
options.add_experimental_option('excludeSwitches', ['enable-automation'])
# 设置个人用户资料的路径 , 可以在chrome的url栏输入 chrome://version/ 查看
user_data_dir = r'--user-data-dir=C:\Users\admin\AppData\Local\Google\Chrome\User Data'
# 配置浏览器路径
options.add_argument(user_data_dir)
# 打开浏览器
web = webdriver.Chrome(options=options)
# 登录qq邮箱
web.get('https://mail.qq.com/')
# 设置wait等待找到发信按钮
mail = WebDriverWait(web, 5).until(lambda x: x.find_element_by_id('composebtn')).click()
# 设置wait等待找到收件人元素
# 不过由于其模块在iframe框
web.switch_to.frame('mainFrame')
address = WebDriverWait(web, 5).until(lambda x: x.find_element_by_css_selector('[aria-label="收件人"]'))
# address.click()
address.send_keys('收件人邮箱')
time.sleep(5) # 设置等待时间,避免因为过快操作被服务器拦截
# 设置wait等待找到主题按钮的元素
subject = WebDriverWait(web, 5).until(lambda x: x.find_element_by_css_selector('[title="主题是一封邮件的标题,可不填。"]'))
# subject.click()
subject.send_keys('主题内容')
time.sleep(5)
# 设置wait等待找到上传附件元素
file_path = "C:\\Users\\admin\\Desktop\\test.txt"
file = web.find_element_by_xpath("//div[@class='input_title']//input[@type='file']")
# print(file.is_enabled())
file.send_keys(file_path)
time.sleep(5)
# 设置wait等待找到富文本元素
# 因为富文本嵌套在iframe中
web.switch_to.frame(web.find_element_by_css_selector('.qmEditorContent>[tabindex="3"]'))
text = WebDriverWait(web, 5).until(lambda x: x.find_element_by_css_selector('[aria-label="正文"]'))
# text.click()
text.send_keys(' 自动化')
time.sleep(5)
# 设置wait等待找到发送按钮
# 需要先把web从frame转换到先以前frame框架中
web.switch_to.parent_frame()
send = WebDriverWait(web, 5).until(lambda x: x.find_element_by_css_selector('[tabindex="5"]'))
send.click()
time.sleep(5)
# 点击发送后判断是否成功
# 使用EC模块证明成功元素存在,元素定位是否存在页面内容中
# 因为其寻找信息也存在frame中
web.switch_to.default_content() # 切换到默认HTML中防止出错
# 切换到需要的frame中去
web.switch_to.frame('mainFrame')
success = ('id', 'sendinfomsg') # 发送成功的元素定位
result = WebDriverWait(web, 8).until(EC.presence_of_element_located(success))
print(result.text) # 查看定位元素的文本内容
time.sleep(10)
web.quit()