how to press enter in selenium python?

2019-04-17 05:18发布

I want to search a special keyword in Instagram. For example, I want to search this word:"fast food". I can send this key in search box. But, when I use submit method in Selenium by Python3, it doesn't work and give me error. This is my code:

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()

This is gave error:

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

Could you help me?

3条回答
仙女界的扛把子
2楼-- · 2019-04-17 05:38
再贱就再见
3楼-- · 2019-04-17 05:38

It need more clicks:

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')
查看更多
小情绪 Triste *
4楼-- · 2019-04-17 05:46

That is very interesting. Another solution is better. It is very important to know that, you must press 2 Enter press on Instagram search box. So, for eliminating while loop, you can use this code: search_button.send_keys("#fast")

time.sleep(5)
search_button.send_keys(u'\ue007')
search_button.send_keys(u'\ue007')
查看更多
登录 后发表回答