前些天有有学员问selenium实现自动登录百度账号出现问题,自动点击用户名登录没有反应,这里给大家贴出代码,供大家参考。
[Python]
纯文本查看
复制代码
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 | from selenium import webdriverb = webdriver.Chrome()b.get('http://www.baidu.com')b.find_element_by_xpath('//*[@id="u1"]/a[7]').click()b.find_element_by_xpath('//*[@id="TANGRAM__PSP_10__footerULoginBtn"]').click()# 输入用户名和密码b.find_element_by_xpath('//*[@id="TANGRAM__PSP_10__userName"]').send_keys('输入百度账户名')b.find_element_by_xpath('//*[@id="TANGRAM__PSP_10__password"]').send_keys('输入百度账户密码')# 点击登录b.find_element_by_id('TANGRAM__PSP_10__submit').click() |
3、运行后,我们发现程序会报出如下错误
[Python]
纯文本查看
复制代码
1 2 3 4 | raise exception_class(message, screen, stacktrace)selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="TANGRAM__PSP_10__footerULoginBtn"]"} (Session info: chrome=75.0.3770.80) (Driver info: chromedriver=75.0.3770.8 (681f24ea911fe754973dda2fdc6d2a2e159dd300-refs/branch-heads/3770@{#40}),platform=Mac OS X 10.13.6 x86_64) |
4、大概意思是程序无法定位到“用户名登录”,我们可以确定我们写的xpath路径是正确的,那是为什么呢?原因是程序执行的很快,在浏览器没加载出“用户名登录”的时候我们程序就开始点击了,那么我们可以在点击前暂停程序2秒钟等待加载完页面,代码如下即可实现自动登录百度账号啦。
[Python]
纯文本查看
复制代码
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 | from selenium import webdriverimport timeb = webdriver.Chrome()b.get('http://www.baidu.com')b.find_element_by_xpath('//*[@id="u1"]/a[7]').click()# 延时两秒,不然无法点击用户名登录time.sleep(2)b.find_element_by_xpath('//*[@id="TANGRAM__PSP_10__footerULoginBtn"]').click()# 输入用户名和密码b.find_element_by_xpath('//*[@id="TANGRAM__PSP_10__userName"]').send_keys('账号')b.find_element_by_xpath('//*[@id="TANGRAM__PSP_10__password"]').send_keys('密码')# 点击登录b.find_element_by_id('TANGRAM__PSP_10__submit').click() |
备注:大家实验时需要将代码中的“账号”、“密码”替换为自己真实的账号和密码。
更多学习资料可关注:itheimaGZ获取