简体   繁体   English

Python - selenium - 如何点击按钮

[英]Python - selenium - how to click on the button

I'm try to code with python, using selenium to do search and click the button.我尝试使用 python 进行编码,使用 selenium 进行搜索并单击按钮。 my code as below:我的代码如下:

from selenium import webdriver
import time 
path = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(path)
driver.get("https://hopamviet.vn")
#import them
# from selenium.webdriver.support.ui import WebDriverWait
# from selenium.webdriver.support import expected_conditions as EC
# from selenium.webdriver.common.by import By
########

# driver.get('http://codepad.org')
# #click radio button - select python
# python_button = driver.find_element_by_xpath("//input[@name='lang' and @value='Python']")
# python_button.click()
# #send text "print('hello world')"
# text_area = driver.find_element_by_id('textarea')
# text_area.send_keys("print('Hello World')")
# #click submit button
# submit_button = driver.find_elements_by_xpath('//*[@id="editor-form"]/table/tbody/tr[3]/td/table/tbody/tr/td/div/table/tbody/tr/td[3]/button')[0]
# submit_button.click()
search = driver.find_element_by_name("song")
search.send_keys("Hello")
search.send_keys(keys.RETURN)

#click search
submit_button = driver.find_elements_by_xpath('/html/body/nav/div/form/div/span/button')
submit_button.click()

for search button, I'm using "find_elements_by_xpath" method to select xpath then click().对于搜索按钮,我使用“find_elements_by_xpath”方法到 select xpath 然后单击()。 but it didn't give me the result as i expected.但它并没有给我预期的结果。 Can you please help look?可以帮忙看看吗? below is HTML code:下面是HTML代码:

在此处输入图像描述

The above line of code上面一行代码

#click search
submit_button = driver.find_elements_by_xpath('/html/body/nav/div/form/div/span/button')
submit_button.click()

is not certainly true, cause you are using find_elements which will return a list in python.不一定是真的,因为您正在使用find_elements ,它将返回 python 中的列表。

Instead use find_element而是使用find_element

#click search
submit_button = driver.find_element_by_xpath('/html/body/nav/div/form/div/span/button')
submit_button.click()

Also, the xpath is absolute, try to use relative xpath like this另外,xpath 是绝对的,尝试使用相对的 xpath 像这样

//i[contains(@class,'search')]//parent::button

full code with explicit waits:具有显式等待的完整代码:

driver.maximize_window()
wait = WebDriverWait(driver, 30)
driver.get("https://hopamviet.vn")
search = wait.until(EC.visibility_of_element_located((By.NAME, "song")))
search.send_keys("Hello")

#click search
submit_button = wait.until(EC.element_to_be_clickable((By.XPATH, "//i[contains(@class,'search')]//parent::button")))
submit_button.click()

Imports:进口:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM