【问题标题】:how to press enter in selenium python?如何在 selenium python 中按 Enter 键?
【发布时间】:2018-03-08 16:44:38
【问题描述】:

我想在 Instagram 中搜索一个特殊关键字。例如,我想搜索这个词:“快餐”。我可以在搜索框中发送此密钥。但是,当我通过 Python3 在 Selenium 中使用提交方法时,它不起作用并给我错误。这是我的代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
import time
driver = webdriver.Firefox()
url="https://www.instagram.com/p/pTPI-kyX7g/?tagged=resurant"
driver.get(url)

#login_button=driver.find_element_by_xpath("""/html/body/span/section/main/article/div[2]/div[2]/p/a""")
#login_button.click()
import time
driver.implicitly_wait(5)
search_button=driver.find_element_by_xpath("""/html/body/span/section/nav/div[2]/div/div/div[2]/input""")
search_button.send_keys("fast food")
search_button.submit()

这是错误的:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: ./ancestor-or-self::form

你能帮帮我吗?

【问题讨论】:

  • 你能提供相关的HTML吗?
  • 在哪个代码行给出了异常。我没有看到异常中提到的带有定位器的代码行。
  • 比之前的代码更完善。你需要xpath吗?

标签: python-3.x selenium submit instagram enter


【解决方案1】:

而不是。 submit() 尝试 '.send_keys(u'\ue007')'

见:http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.keys

【讨论】:

  • 它不起作用。只有错误被删除,搜索新闻没有按下
  • 你的解决方法类似于我的一种方式:search_button.send_keys("fast",Keys.RETURN)
  • 在您的问题中分享您已经尝试解决问题的所有内容是一种很好的做法。
  • 这里有很多关于不同语言的 SendKeys 问题的信息:stackoverflow.com/questions/1629053/…
  • 我可以解决它,我在答案框中分享我的回答
【解决方案2】:

需要更多点击:

search_button=driver.find_element_by_xpath("""/html/body/span/section/nav/div[2]/div/div/div[2]/input""")

    search_button.send_keys("fast")
    while True:
        search_button.send_keys(u'\ue007')

【讨论】:

    【解决方案3】:

    这很有趣。另一种解决方案更好。知道这一点非常重要,您必须在 Instagram 搜索框中按 2 Enter。因此,为了消除 while 循环,您可以使用以下代码: search_button.send_keys("#fast")

    time.sleep(5)
    search_button.send_keys(u'\ue007')
    search_button.send_keys(u'\ue007')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-07
      • 2012-05-01
      • 1970-01-01
      • 2023-03-12
      • 2015-06-28
      • 1970-01-01
      • 2016-10-16
      • 1970-01-01
      相关资源
      最近更新 更多