使用带有 python 的 selenium 登录网站

Logging into website using selenium with python

我正在尝试使用 selenium 登录此网站: 但它说密码和登录名不可见。我环顾四周,看到有人说要等待,但等待似乎无济于事。这是我的代码:

    # importing libraries
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import re, time, csv


driver = webdriver.Firefox()

driver.get("https://platform.openquake.org/account/login/")
driver.switch_to
driver.maximize_window
time.sleep(10)

username = driver.find_element_by_xpath("//input[@name='username']")
username.send_keys("hi there")

错误信息是:

ElementNotVisibleException: Element is not currently visible and so may not be interacted with

修改你的xpath:

username = driver.find_element_by_xpath("//div[@class='controls']/input[@id='id_username']")

您的 XPATH 实际上匹配两个元素。非复数驱动程序方法 (find_element_by_XXX) return 他们找到匹配的第一个元素,在这种情况下不是您想要的。

对于这种情况,一个很好的调试工具是使用复数形式 (find_elements_by_XXX),然后查看有多少元素匹配。

在这种情况下,您应该按照 Tanu 的建议并使用更严格的 XPATH:

username = driver.find_element_by_xpath("//div[@class='controls']/input[@id='id_username']")
password = driver.find_element_by_xpath("//div[@class='controls']/input[@id='id_password']")