Python / Selenium:点击此特定按钮的不同方式

时间:2018-02-27 18:36:40

标签: python selenium

我正在尝试理解Python,因为我刚刚使用VBA切换。我对可能解决这个问题的方法感兴趣。我已经通过直接转到链接来解决这个问题,但我需要了解并在此处申请。

from selenium import webdriver

chromedriver = r'C:\Users\dd\Desktop\chromedriver.exe'
browser = webdriver.Chrome(chromedriver)
url = 'https://www.fake.com/'

browser.get(url)

browser.find_element_by_id('txtLoginUserName').send_keys("Hello")
browser.find_element_by_id('txtLoginPassword').send_keys("There")
browser.find_element_by_id('btnLogin').click()

此时,我正在尝试导航到特定的按钮/链接。 以下是页面/元素

中的信息
 <a href="javascript:void(0)" style="text-decoration:none" onclick="InitiateCallBack('187', 'True', 'T-Mobile', 'https://www.fake.com/', 'TMobile')">T-Mobile</a>

以下是我尝试过的一些事情:

for elem in browser.find_elements_by_xpath("//*[contains(text(), 'T-Mobile')]"):
    elem.click

browser.execute_script("InitiateCallBack(187, True, T-Mobile, https://www.fake.com/, TMobile)")

我还试图寻找标签并使用css选择器,所有这些都是我从挫折中删除的!

具体问题

  1. 如何使用innertext“T-Mobile”点击按钮?
  2. 我将如何执行onclick事件?
  3. 我试过阅读以下链接,但仍然没有以不同的方式成功传入。部分原因可能是因为我还不了解具体的语法。这只是我看过的一些事情。在我来到这里之前,我花了大约3个小时尝试各种各样的事情!

    selenium python onclick() gives StaleElementReferenceException http://selenium-python.readthedocs.io/locating-elements.html Python: Selenium to simulate onclick https://stackoverflow.com/questions/43531654/simulate-a-onclick-with-selenium-https://stackoverflow.com/questions/45360707/python-selenium-using-onclick Running javascript in Selenium using Python

3 个答案:

答案 0 :(得分:2)

  

如何利用innertext“T-Mobile”点击按钮?

find_elements_by_link_text适用于此案例。

elements = driver.find_elements_by_link_text('T-Mobile')
for elem in elements:
    elem.click()

如果您没有完整的确切文字,也会有一个by_partial_link_text定位器。

  

我如何执行onclick事件?

最简单的方法是简单地在元素上调用.click(),如上所示,事件当然应该在那时执行。

或者,您可以检索onclick属性并使用driver.execute_script来运行js。

for elem in elements:
    script = elem.get_attribute('onlcick')
    driver.execute_script(script)

编辑:

请注意,在您的代码中,您执行了element.click - 这没有任何作用。 element.click()(注意parens)调用click方法。

  

有没有办法利用browser.execute_script()进行onclick事件

execute_script可以触发等效事件,但可能会有更多的侦听器通过这样做而错过。使用元素单击方法是最健全的。可能会有很多网站的实施细节可能会妨碍您的自动化工作,但这些可能性是无穷无尽的。没有看到实际情况,很难说 您可以使用JS方法单击元素或以其他方式与页面交互,但您可能会错过在“正常”使用网站时发生的某些事件监听器;你想或多或少地模仿正常使用。

答案 1 :(得分:1)

根据 HTML ,您已经分享了网站使用 JavaScript 。因此,对于带有 T-Mobile 文字的链接上的click(),您必须使用expected_conditions子句{em}来引导 WebDriverWait 可以使用以下代码块:

element_to_be_clickable

答案 2 :(得分:1)

你可以使用它

xmemory