每当我尝试执行以下错误时,我都会尝试使用selenium访问网站:
ElementNotVisibleException: Message: element not visible
代码如下:
from urllib import parse
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
class ICAIScraper(object):
def __init__(self):
self.url = "https://www.icaionlineregistration.org/Admin_Module/Login.aspx"
self.driver = webdriver.Chrome('C:\\chromedriver.exe')
def scrape(self):
self.driver.get(self.url)
wait = WebDriverWait(self.driver, 10)
wait.until(lambda driver: driver.find_element_by_id('txt_username').is_displayed() == False)
print('Yay! on the first page')
username = self.driver.find_element_by_id('txt_username')
username.click()
username.send_keys('username')
password = self.driver.find_element_by_id('txt_password')
password.send_keys('password')
password.send_keys(Keys.ENTER)
self.driver.quit()
if __name__ == '__main__':
scraper = ICAIScraper()
scraper.scrape()
答案 0 :(得分:0)
编写一个简单的函数,通过id滚动到任何UI元素(或者您可以使用By
类来自定义它)。通过提供元素的id
属性来调用该方法将使元素成为driver
的焦点。
def scroll_to_element_by_id(driver, element_id):
driver.execute_script("return arguments[0].scrollIntoView();", driver.find_element_by_id(element_id))
示例调用:
scroll_to_element_by_id(self.driver, 'txt_password')
答案 1 :(得分:0)
错误说明了一切:
ElementNotVisibleException: Message: element not visible
由于您尝试通过Username
属性找到Password
和id
字段,因此字段未唯一标识。因此,我们必须采用Locator Strategy
来唯一标识Username
和Password
字段,如下所示:
# populate the Username field
self.driver.find_element_by_xpath("//td/img[@src='../images/login_userName.png']//following::input[2]").send_keys("username")
# populate the Password field
self.driver.find_element_by_xpath("//td/img[@src='../images/login_password.png']//following::input[2]").send_keys("password")