使用Selenium Webdriver对网页进行操作时,碰到“An element command could not be completed because the element is not visible on the page.”的报错,原因有三:
1.将被执行操作的元素没有被展示出来,需要将浏览器窗口放大,或滚动条下拉。
browsertest.maximize_window()
target =browsertest.find_element_by_class_name("card text-center col-md-4")
browsertest.execute_script("arguments[0].scrollIntoView()", target) #拖动到可见的元素去
2.页面中有名字相同的元素,重名元素在页面下方未被展示出来,因此就算放大了浏览器窗口、滚动条下拉,还是会有ElementNotVisible的报错。对元素上级进行限定即可:
target =browsertest.find_element_by_class_name("card text-center col-md-4")
linkElem=target.find_element_by_link_text('Automate the Boring Stuff with Python')
#原先上面这行是linkElem=browsertest.find_element_by_link_text('Automate the Boring Stuff with Python'),对整个网页进行find_element_by_link_text,得到了未被展示出的结果
print(type(linkElem))
3.存在页面内跳转,需要等几秒再进行下一步操作,使用time.sleep()实现
from selenium import webdriver
import time
browser=webdriver.Safari()
browser.get('https://login.live.com')
emailElem=browser.find_element_by_class_name('placeholder')
emailElem.send_keys('emailadress@outlook.com')
emailclick=browser.find_element_by_class_name('btn btn-block btn-primary')
emailclick.click()
time.sleep(5)
emailPassword=browser.find_element_by_class_name('placeholder') #没有加time.sleep()的时候这里会有找不到元素的报错
emailPassword.send_keys('mypassword')
emailPasswordClick=browser.find_element_by_class_name('btn btn-block btn-primary')
emailPasswordClick.click()