【问题标题】:Issue clicking Javascript button with python/Selenium使用 python/Selenium 单击 Javascript 按钮时出现问题
【发布时间】:2019-05-28 02:27:30
【问题描述】:

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

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

当我打印“按钮”时,代码似乎定位了一个元素,我得到了一个元素对象。

我尝试使用 driver.execute_script 来执行 onclick= 属性,但这也没有任何作用。

感谢任何帮助。

【问题讨论】:

  • 你问你是否有错误的元素......你确实想要JS的onClick会做......但我认为的主要问题是,你正在使用find_elements_by_xpath您应该使用不带“S”的find_element_by_xpath...

标签: python selenium web-scraping


【解决方案1】:

使用WebDriverWaitexpected_conditions 是一个好习惯!

explicit-waits

这对我有用:

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 有关,您应该使用 find_element_by_xpath 而不使用 s...

【讨论】:

    【解决方案2】:

    以下对我有用

    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 动作。因此,如果您使用这种方法进行网络测试,您可能会错过大量错误

    【讨论】:

    • 这也有效!我确实认为最好使用webdriverfind_element 方法而不是execute_script 如果我错了请纠正我...
    • 谢谢你这样做。我只是没有找到正确的元素吗?
    • 你应该再次警告 OP 使用execute_script 来单击元素可能存在的缺点。如果 OP 从事 web 应用程序测试 - 不应该使用这种方法!
    • @Andersson 我是 python 新手,所以感谢任何关于该警告的建议和更多信息。
    • @MosheSlavin 的回答应该被接受,而不是这个,
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2017-05-28
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 2011-03-09
    相关资源
    最近更新 更多