如何使用Python Selenium在文本框(输入)中定位和插入值?


84

我具有以下HTML结构,并且尝试使用Selenium输入值NUM

<div class="MY_HEADING_A">
    <div class="TitleA">My title</div>
    <div class="Foobar"></div>
        <div class="PageFrame" area="W">                
             <span class="PageText">PAGE <input id="a1" type="txt" NUM="" />  of <span id="MAX"></span> </span>
</div>

这是我编写的代码:

head = driver.find_element_by_class_name("MY_HEADING_A")
frame_elem = head.find_element_by_class_name("PageText")

# Following is a pseudo code. 
# Basically I need to enter a value of 1, 2, 3 etc in the textbox field (NUM) 
# and then hit RETURN key.
## txt  = frame_elem.find_element_by_name("NUM")
## txt.send_keys(Key.4"

如何获取此元素并输入值?

Answers:


147

假设您的页面在“ http://example.com ”下可用

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

按ID选择元素:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

现在您可以模拟击回车键:

inputElement.send_keys(Keys.ENTER)

或者,如果您是一种表格,您可以提交:

inputElement.submit() 

3
ElementNotInteractableException:消息:元素
Sheshank S.18年

键盘无法到达
Sheshank S.

3
交互之前,您应该等待该元素出现。input_element = WebDriverWait(驱动程序,WAIT_TIME).until(EC.visibility_of_element_located((By.CSS_SELECTOR,“#a1”)))input_element.send_keys(“ 1”)
Wildhammer
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.