为什么我在尝试使用Selenium选择搜索栏时收到"element not interactable"错误?



这里的初学者试图使用自动化无聊的东西来学习Python。

作为实践,我正在尝试创建一个程序,该程序将在网站上搜索给定的食品,并确定该食品的成分中是否包含特定成分。 我用来搜索的网站是 https://world.openfoodfacts.org/。

我想做的是从用户那里获取输入,然后将其输入到网站的搜索栏中。 我能够使用硒识别搜索栏元素,但是当我尝试输入它时,出现以下错误:

File "C:/Users/black/AppData/Local/Programs/Python/Python38-32/harambes revenge.py", line 37, in <module>
searchbar.send_keys('%s' % product)
File "C:UsersblackAppDataRoamingPythonPython38site-packagesseleniumwebdriverremotewebelement.py", line 477, in send_keys
self._execute(Command.SEND_KEYS_TO_ELEMENT,
File "C:UsersblackAppDataRoamingPythonPython38site-packagesseleniumwebdriverremotewebelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "C:UsersblackAppDataRoamingPythonPython38site-packagesseleniumwebdriverremotewebdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:UsersblackAppDataRoamingPythonPython38site-packagesseleniumwebdriverremoteerrorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable
(Session info: chrome=83.0.4103.97)

我目前的理论是,这与网站上的搜索栏根据窗口是否最大化而改变位置有关。 不幸的是,我对 HTML 或 CSS 了解不多(但通过对此进行故障排除,我学到了很多东西!

这是我的代码,感谢您查看,如果您有任何想法,请告诉我!

product = pyip.inputStr('What product do we want to take a look at?')
browser = webdriver.Chrome()
browser.get('https://world.openfoodfacts.org/')
browser.implicitly_wait(5) #a google search told me to try this, no effect
try:
searchbar = browser.find_element_by_name('search_terms')
print('found element %s' % searchbar) #able to find element
except:
print('could not find element')
searchbar.send_keys('%s' % product)

元素位于可见页面之外。处理此问题的一种快速方法是最大化窗口。

browser = webdriver.Chrome()
browser.maximize_window()
# rest of your code

您可以通过将其设置为实例化Chrome的选项来执行相同的操作:

options=webdriver.ChromeOptions()
options.add_argument('start-maximized')
browser = webdriver.Chrome(options=options)
# rest of your code

第三种方法是使用ActionChains.move_to_element并使Web元素成为焦点。

最新更新