目标
由于每次登录还要输入账号和密码,这样太麻烦了,为了节约时间用自动化控制软件控制浏览器来登录作家助手。
项目准备
软件:Pycharm
第三方库:selenium
网站地址:https://write.qq.com/public/login.html?authortip=0
项目分析
打开网站。
这个有账号登录,QQ登录和微信登录。因为我之前用QQ注册过,所以就用QQ登录的方式。
点击前去登录QQ。
会得到这样一个页面。
把网址复制下来备用。
代码实现
#导入第三方库selenium
from selenium import webdriver
#引入自动化控制程序chromedriver.exe
driver=webdriver.Chrome(executable_path=r'C:\Users\acer\AppData\Local\Google\Chrome\Application\chromedriver.exe')
driver.get('https://graph.qq.com/oauth2.0/show?which=Login&display=pc&g_ut=1&response_type=code&redirect_uri=https%3A%2F%2Fptlogin.qidian.com%2Flogin%2Fqqconnectcallback%3Freturnurl%3Dhttps%253A%252F%252Fwrite.qq.com%253Fartidx%253D0%26appid%3D34%26areaid%3D1006%26jumpdm%3Dyuewen%26popup%3D1%26ajaxdm%3Dyuewen%26target%3Dtop%26ticket%3D1%26ish5%3D0%26auto%3D1%26autotime%3D7&client_id=101481755')#刚刚复制的url
测试一下
最大化显示。
driver.maximize_window()#最大化窗口
切换iframe
复制下它的id。
#切换iframe
ptlogin_iframe=driver.find_element_by_id('ptlogin_iframe')
driver.switch_to.frame(ptlogin_iframe)#switch_to.frame()切换iframe,之前用的是switch_to_iframe()现在修改了
driver.find_element_by_id('switcher_plogin').click()#复制下来的id .click()模拟鼠标点击
测试一下。
接下来模拟输入账号和密码。
driver.find_element_by_xpath('//*[@id="u"]').send_keys('账号')
driver.find_element_by_xpath('//*[@id="p"]').send_keys('密码')
driver.find_element_by_xpath('//*[@id="login_button"]').click()#模拟点击登录
效果显示
登录成功。
在这里没有遇到验证码的问题,等接下来的测试中试一下验证码问题。
完整代码如下:
from selenium import webdriver
driver=webdriver.Chrome(executable_path=r'C:\Users\acer\AppData\Local\Google\Chrome\Application\chromedriver.exe')
driver.get('https://graph.qq.com/oauth2.0/show?which=Login&display=pc&g_ut=1&response_type=code&redirect_uri=https%3A%2F%2Fptlogin.qidian.com%2Flogin%2Fqqconnectcallback%3Freturnurl%3Dhttps%253A%252F%252Fwrite.qq.com%253Fartidx%253D0%26appid%3D34%26areaid%3D1006%26jumpdm%3Dyuewen%26popup%3D1%26ajaxdm%3Dyuewen%26target%3Dtop%26ticket%3D1%26ish5%3D0%26auto%3D1%26autotime%3D7&client_id=101481755')
driver.maximize_window()
#切换iframe
ptlogin_iframe=driver.find_element_by_id('ptlogin_iframe')
driver.switch_to.frame(ptlogin_iframe)
driver.find_element_by_id('switcher_plogin').click()
driver.find_element_by_xpath('//*[@id="u"]').send_keys('账号')
driver.find_element_by_xpath('//*[@id="p"]').send_keys('密码')
driver.find_element_by_xpath('//*[@id="login_button"]').click()