Python Selenium - 如何点击javascript按钮

时间:2013-11-11 00:44:23

标签: python selenium

我是Python和Selenium的新手。我的网站上有一个按钮的代码如下,我无法使用

点击它
 driver.find_element_by_id("AddToBasket").click()

driver.find_element_by_xpath("//a[@id='AddToCartButton']").click()

将鼠标悬停在按钮上只会显示javascript:void(0)

所以这是我的代码

<div class="add">
    <a href="javascript:void(0)" id="AddToBasket" class="addtobtn addtobag">
      <span>Add to cart</span>
    </a>

感谢。

1 个答案:

答案 0 :(得分:6)

from selenium.webdriver.common.action_chains import ActionChains
self.driver = webdriver.Firefox()
# You need a mouse to hover the span elements here
self.mouse = webdriver.ActionChains(self.driver)    

# You need get the span element from its xpath:
value = 'Add to cart'
span_xpath = '//span[contains(text(), "' + value + '")]'
span_element = driver.find_element_by_xpath(span_xpath)

# Then you hover on span element by mouse and click on it:
self.mouse.move_to_element(span_element).click().perform()