使用Python/Selenium点击JavaScript按钮出现问题

5
我正在尝试在以下链接中点击标有“Pickup”的按钮:

https://firehouse.alohaorderonline.com/StartOrder.aspx?SelectMenuType=Retail&SelectMenu=1000560&SelectSite=01291

我的代码如下,但是什么也没有发生,直到它以错误的形式失败,报错信息为“元素不可交互”。
pickupurl = 'https://firehouse.alohaorderonline.com/StartOrder.aspx?SelectMenuType=Retail&SelectMenu=1000560&SelectSite=1291'

driver = webdriver.Chrome('d:\\chromedriver\\chromedriver.exe')
driver.implicitly_wait(80)
driver.get(pickupurl)



button = driver.find_elements_by_xpath('//*[@id="ctl00_ctl00_PickupButton"]')
button.click()

代码似乎可以定位一个元素,当我打印'button'时,我得到了一个元素对象。
我尝试使用driver.execute_script来执行onclick属性,但这也没有任何作用。
感谢您的帮助。

你问自己是否选错了元素...你想要执行JS的onClick所做的事...但我认为主要问题是,你正在使用find_elements_by_xpath而不是find_element_by_xpath,删掉"S"即可。 - Moshe Slavin
2个回答

4

使用WebDriverWaitexpected_conditions是一个好的实践方法!

请查看明确等待

这对我来说很有效:

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

pickupurl = 'https://firehouse.alohaorderonline.com/StartOrder.aspx?SelectMenuType=Retail&SelectMenu=1000560&SelectSite=1291'
driver = webdriver.Chrome('d:\\chromedriver\\chromedriver.exe')
driver.get(pickupurl)
wait = WebDriverWait(driver, 10)
pickup_button = wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@id='btnPickupDiv']/div[@class='Button']")))

pickup_button.click()
loacter = wait.until(EC.presence_of_element_located((By.CLASS_NAME, "AddressZipLabelDiv")))
driver.quit()

你遇到的问题可能与 find_elements_by_xpath 有关,你应该使用没有 sfind_element_by_xpath...


3
下面的方法适用于我:
from selenium import webdriver

d = webdriver.Chrome()
url = 'https://firehouse.alohaorderonline.com/StartOrder.aspx?SelectMenuType=Retail&SelectMenu=1000560&SelectSite=01291'
d.get(url)
d.execute_script('document.getElementById("ctl00_ctl00_Content_Content_btnPickup").click();')

@Andersson的有用警告

通过execute_script执行的element.click()并不会真正地进行点击,而只是触发元素(链接、输入框、按钮等)的onclick操作。因此,如果您在进行Web测试时使用此方法,可能会错过很多错误。


这也可以工作!我认为最好使用webdriverfind_element方法而不是execute_script,如果我错了请纠正我... - Moshe Slavin
谢谢,解决了。是我没有定位到正确的元素吗? - 3030tank
2
你应该再次警告OP关于使用execute_script点击元素可能存在的缺点。如果OP从事Web应用程序测试 - 不应该使用这种方法! - Andersson
@Andersson 我是一个 Python 新手,所以非常感谢您的建议和更多关于那个警告的信息。 - QHarr
这实际上与Python无关,而是与JS有关。通过execute_script执行的element.click()并不真正进行点击,而只是触发元素(链接、输入框、按钮等)的onclick操作。因此,如果您在Web测试中使用此方法,可能会错过大量的错误... - Andersson
3
应该接受@MosheSlavin的答案,而不是这个答案。 - Corey Goldberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接