【问题标题】:Why am I getting an "element not interactable" error when trying to select a search bar using selenium?为什么在尝试使用 selenium 选择搜索栏时出现“元素不可交互”错误?
【发布时间】:2020-06-10 00:52:21
【问题描述】:

这里的所有初学者都在尝试使用 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)

【问题讨论】:

    标签: python selenium selenium-webdriver


    【解决方案1】:

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

    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 并将网络元素置于焦点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2021-03-03
      • 2020-02-07
      • 2019-07-04
      • 2020-08-26
      • 1970-01-01
      • 2019-07-12
      相关资源
      最近更新 更多