![](/img/trans.png)
[英]How to locate and insert a value in a text box (input) using Python Selenium?
[英]How to insert a value in text box using Python Selenium
我有以下 HTML 結構,我正在嘗試使用 Selenium 輸入一個值
<div class="form-group justify-content-center d-flex">
<form id="main-form" class="form-inline" action="/pushData" method="post">
<input type="hidden" name="_token" value="bnePp0JmVaVYuaTIAfuVIGT2y7usVssX3vQrAGaz">
<input type="text" id="input-url" class="url-input" name="url" placeholder="Paste URL to shorten">
<button class="button main-btn main-btn_primary" id="button-submit">Cut</button>
</form>
</div>
這是我的代碼
driver.find_element_by_id("input-url").send_keys("test")
driver.find_element_by_id("button-submit").click()
我想獲取這個元素並輸入一個值。
按 id 選擇元素:
inputElement = driver.find_element_by_id("input-url")
inputElement.send_keys('testing')
現在您可以模擬按 ENTER 鍵:
inputElement.send_keys(Keys.ENTER)
或者如果它是一個表格,您可以提交:
inputElement.submit()
Selenium 4.3.0:不推薦使用的 find_element_by_* 和 find_elements_by_* 現在已刪除 (#10712)
以下代碼將起作用:
[..]
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
[..]
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 'input-url'))).send_keys('test')
button_to_be_clicked = browser.find_element(By.ID, 'button-submit')
button_to_be_clicked.click()
要將字符序列發送到<input>
元素,您可以使用以下任一定位器策略:
使用css_selector :
driver.find_element(By.CSS_SELECTOR, "input.url-input#input-url[name='url'][placeholder='Paste URL to shorten']").send_keys("Phonex")
使用xpath :
driver.find_element(By.XPATH, "//input[@class='url-input' and @id='input-url'][@name='url' and @placeholder='Paste URL to shorten']").send_keys("Phonex")
理想情況下,要將字符序列發送到<input>
元素,您需要為element_to_be_clickable()引入WebDriverWait ,並且可以使用以下任一定位器策略:
使用CSS_SELECTOR :
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.url-input#input-url[name='url'][placeholder='Paste URL to shorten']"))).send_keys("Phonex")
使用XPATH :
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='url-input' and @id='input-url'][@name='url' and @placeholder='Paste URL to shorten']"))).send_keys("Phonex")
注意:您必須添加以下導入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.