使用Python Selenium无法填充表单Tag字段求助
你遇到的问题是定位错了元素——你选中的是标签组件的外层容器div,而实际接收输入的是容器内部的<input>元素。bootstrap-tagsinput这类组件会把真实的输入框嵌套在容器里,直接操作外层div无法完成输入。
修改方案:
- 修正元素定位:直接定位到
bootstrap-tagsinput容器内的input元素 - 用显式等待替代固定sleep(可选但推荐,避免因页面加载慢导致的元素找不到问题)
修改后的代码:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys from time import sleep # 打开网站并登录 driver = webdriver.Firefox() driver.get("https://socialbookmarking.agency/") sleep(1) link = driver.find_element(By.LINK_TEXT, 'Sign in') link.click() sleep(1) email = driver.find_element(By.NAME, "username_or_email") email.send_keys("test@test.com") sleep(1) password = driver.find_element(By.NAME, "password") password.send_keys("testpassword") sleep(1) driver.find_element(By.XPATH, '//button[@type="submit"][1]').click() sleep(2) # 进入表单页面 driver.get("https://socialbookmarking.agency/submit-listing/details/") # 定位表单字段 title = driver.find_element(By.NAME, "title") location = driver.find_element(By.NAME, "location") website_url = driver.find_element(By.NAME, "website_url") country = driver.find_element(By.NAME, "country") small_description = driver.find_element(By.NAME, "small_description") description = driver.find_element(By.NAME, "description") # 关键修改:定位标签组件内的真实input元素,并用显式等待确保元素可交互 wait = WebDriverWait(driver, 10) newtag = wait.until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@class, 'bootstrap-tagsinput')]/input"))) # 填充表单 title.send_keys("Our First Test post") sleep(1) location.send_keys("Melbourne") sleep(1) website_url.send_keys("www.firstpost.com") sleep(1) country.send_keys("Australia") sleep(1) small_description.send_keys("This is the few line of test small description") sleep(1) description.send_keys("This is the few line of test description, you can add more content here! not sure about limit ") sleep(1) # 向input元素发送标签文本 newtag.send_keys("test") # 如需添加多个标签,发送文本后按回车即可 # newtag.send_keys("test" + Keys.ENTER) # newtag.send_keys("another-tag" + Keys.ENTER) sleep(1) driver.find_element(By.XPATH, '//button[@type="submit"][1]').click() sleep(2) driver.quit()
补充说明:
- 如果需要添加多个标签,在发送每个标签文本后模拟按下回车键,组件会自动把输入的文本转为独立标签。
- 显式等待
WebDriverWait会等待元素可交互后再操作,比固定sleep更可靠,适合处理动态加载的页面元素。
内容的提问来源于stack exchange,提问作者manikanta gowda
相关产品推荐
相关产品推荐

