首页 > 解决方案 > 为什么在尝试使用 selenium 选择搜索栏时出现“元素不可交互”错误?

问题描述

在这里尝试使用 Automate The Boring Stuff 学习 Python 的初学者。

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

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

  File "C:/Users/black/AppData/Local/Programs/Python/Python38-32/harambes revenge.py", line 37, in <module>
    searchbar.send_keys('%s' % product)
  File "C:\Users\black\AppData\Roaming\Python\Python38\site-packages\selenium\webdriver\remote\webelement.py", line 477, in send_keys
    self._execute(Command.SEND_KEYS_TO_ELEMENT,
  File "C:\Users\black\AppData\Roaming\Python\Python38\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\black\AppData\Roaming\Python\Python38\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\black\AppData\Roaming\Python\Python38\site-packages\selenium\webdriver\remote\errorhandler.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)

标签: pythonseleniumselenium-webdriver

解决方案


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

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_elementwebelement 并使之成为焦点。


推荐阅读