首页 > 解决方案 > 在 Python 中使用 Selenium 将密钥发送到文本框不起作用

问题描述

我正在尝试将文本设置为以下文本框-

<input type="text" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="off" spellcheck="false" tabindex="0" aria-label="First name" name="firstName" value="" autocapitalize="sentences" id="firstName" data-initial-value="" badinput="false">

通过使用以下 python 代码-

import time
import pandas as pd
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

exe_path = '/usr/local/bin/chromedriver'

driver = webdriver.Chrome(exe_path)
driver.implicitly_wait(10)


driver.get('https://support.google.com/mail/answer/56256?hl=en')
driver.find_element_by_class_name('action-button').click()

f = driver.find_element_by_id('firstName').send_keys('hfsjdkhf')

它确实找到了元素,但是光标只是在那里停留了一段时间,我收到以下错误-

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="firstName"]"}
  (Session info: chrome=80.0.3987.132)

我该如何解决??

标签: pythonseleniumselenium-webdriver

解决方案


问题是,在单击action-button打开一个新选项卡的 之后,selenium 继续在旧选项卡上处于活动状态,正如您可以通过使用看到的那样print(driver.current_url),解决方案正在等待几秒钟,然后使用 切换到新选项卡driver.switch_to_window(driver.window_handles[1]),即:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

exe_path = '/usr/local/bin/chromedriver'
driver = webdriver.Chrome(exe_path)
wait = WebDriverWait(driver, 10)

driver.get('https://support.google.com/mail/answer/56256?hl=en')
el = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "action-button")))
el.click()
wait.until(EC.number_of_windows_to_be(2)) # wait new tab
driver.switch_to_window(driver.window_handles[1]) # switch to newly opened tab
# now you can send the keys to id firstName
el = wait.until(EC.element_to_be_clickable((By.ID, "firstName")))
el.send_keys('username')

推荐阅读