python - 在 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)
我该如何解决??
解决方案
问题是,在单击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')
推荐阅读
- javascript - 如何在primeng contextMenu中取消选择使用右键单击选择的行?
- c# - 事件不会一直从线程触发到主线程
- angular - 使用 [(NgModel)] 更改绑定 Angular 表中的值会影响其他字段
- powershell - 使用 Powershell 在现有 BizTalk 应用程序中创建接收位置和发送端口
- python - 有没有办法使用 Talisman 将 content_security_policy 删除为 none?
- hadoop - 无法为 ZooKeeper 中的任何服务器 URI 打开客户端传输:GSS 启动失败——beeline 或 hive2 没有问题
- php - 使用 Ajax 在控件中返回视图
- python - 如何一次在pysftp中写入文件
- c# - AutoCompleteStringCollection - API - 问题的
- css - 增加图标的大小而不增加同一按钮内的文本大小>(文本+图标)>仅增加图标