Selenium - 无法与输入框交互
我正在使用Python的Selenium库,想要在“https://www.screener.in/explore/”这个页面上进行操作。这个页面有一个输入框,可以用来搜索公司名称。但是我的代码出现了一个错误,错误信息是“raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable”。
下面是我用Python写的代码
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.screener.in/explore/")
button = driver.find_element(By.XPATH, "//input[@class='u-full-width']")
button.send_keys("TCS")
time.sleep(100)
从网页的HTML源代码中,我找到了输入框的标签
<input
aria-label="Search for a company"
type="search"
autocomplete="off"
spellcheck="false"
placeholder="Search for a company"
class="u-full-width"
data-company-search="true">
我的目标是想在这个输入框里搜索公司,然后页面会跳转到公司的详细信息页面。
1 个回答
1
你使用了错误的元素。
你从定位器获取的输入是针对移动视图的,而这个输入在网页视图中是隐藏的(根据你的尺寸设置)。因为它是隐藏的,所以没有大小和位置,因此无法进行操作。
你可以通过这个定位器过滤出可见的输入,然后使用第一个可见的输入。
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
URL = "https://www.screener.in/company/compare/00000085/"
driver = webdriver.Chrome()
driver.get(URL)
company_inputs = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'input[type=search]')))
visible_input = [element for element in company_inputs if element.is_displayed()][0]
visible_input.click()
visible_input.send_keys('Boeing')