Selenium / Python:无法使用任何find_element_by_ *方法查找元素

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Selenium / Python:无法使用任何find_element_by_ *方法查找元素相关的知识,希望对你有一定的参考价值。

我面临一个奇怪的挑战 - 可能与我对html的不充分理解有关。

我需要从网站上提取一些数据。但我在某种程度上无法通过登录步骤 - 尽管过去曾为其他几个类似的应用程序使用了类似的代码。我无法使用任何get_element_by _ *()方法找到用户名或密码元素。过去24小时我一直在尝试各种各样的事情和研究。我确信我在这里做了一些根本错误的事情 - 但是无法弄清楚是什么。我有非常相似的代码,我可以毫无困难地登录到不同的网站(http://courtbooking.bayclubs.com)。

救命!我正在复制并粘贴代码的相关部分

url = "https://www.ussquash.com/serve/?program=login"
inp_username = "my-username"
inp_password = "my-password"
try:
    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    driver = webdriver.Chrome(chrome_options=options)
except:
    print("No web driver")
    exit()

try:
    driver.get(url)
except:
    print("Could not load URL")
    exit()

time.sleep(wait_time_in_seconds)

try:
    #user = driver.find_element_by_id("login")
    user = driver.find_element_by_name("username")
except Exception as e:
    print("No username element, error {}".format(e))
    exit()
else:
    print("Username element found")

try:
    password = driver.find_element_by_id("loginpass")
except Exception as e:
    print("No password element, error {}".format(e))
    exit()
else:
    print("Password element found")

try:
    signon_button = WebDriverWait(driver, wait_time_in_seconds).until(
                            EC.presence_of_element_located((By.CLASS_NAME, "btn btn-primary login-btn")))
except:
    print("No signon element")
    exit()
else:
    print("Signon element found")


print("Logging in with username: %s, password: %s", inp_username, inp_password)
user.clear()
user.send_keys(inp_username)
password.clear()
password.send_keys(inp_password)
signon_button.click()
答案

该网站使用iFrames作为登录部分,因此首先需要切换到iframe

driver.switch_to_frame(iframe)

然后选择所需的元素。希望这有助于[Link]

以上是关于Selenium / Python:无法使用任何find_element_by_ *方法查找元素的主要内容,如果未能解决你的问题,请参考以下文章

如何通过 Python 使用 GeckoDriver 和 Firefox 使 Selenium 脚本无法检测?

Selenium 使用 css、xpath、name、id (python) 找不到任何元素

带有Python的Selenium Webdriver - 无法使用Selenium Web驱动程序在Web应用程序中提供输入(Date)

Python Selenium 无法从 mpob 网站检索标签内容

记Selenium HTMLTestRunner 无法生成测试报告的总结

使用 selenium 和 python 检查是不是存在任何警报