如何使用Selenium和Python按HTML单击按钮

时间:2018-09-08 08:41:34

标签: python selenium selenium-webdriver webdriver webdriverwait

我正在学习Selenium,并尝试单击awk -F , -v OFS=, '{ x = $6; NF = 5; $1 = $1; print; $5 = x; print }' 按钮: https://speedtest.telstra.com/

GO

有什么可能的Selenium方法来使该按钮被点击, <button class="button background-primary-hover text-primary" aria-label="start your speedtest"> <span style="font-size: unset; overflow-wrap: unset;">GO</span></button> .... ???

我也想看看我发现了什么,所以应该使用elem = driver.find_element_by_吗?

3 个答案:

答案 0 :(得分:2)

根据网站https://speedtest.telstra.com/,所需元素位于<iframe>中,因此您需要诱使 WebDriverWait 切换到<iframe>,然后注意元素,则可以使用以下解决方案:

  • 使用XPATH

    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@class='speed-test' and @src='//telstra-nbn.speedtestcustom.com']")))
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='button background-primary-hover text-primary']/span[contains(.,'GO')]"))).click()
    
  • 使用CSS_SELECTOR

    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"//iframe.speed-test[src*='speedtestcustom']")))
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.button.background-primary-hover.text-primary[aria-label='start your speedtest']>span"))).click()
    

注意:您必须添加以下导入:

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

答案 1 :(得分:0)

您必须使用xpath,其中有xpath用于Chrome的帮助程序工具。您可以安装它。

button = driver.find_element_by_xpath("your xpath")

button.click()

答案 2 :(得分:-1)

尝试一下:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>input field of number</p>
<input type="number" class="number-val">
<ul class="number-list">
  <li>1-10</li>
  <li>11-20</li>
  <li>21-40</li>
  <li>41-50</li>
  <li>51-60</li>
  <li>61-80</li>
  <li>81-100</li>
  <li>101-</li>
</ul>

因为它将选择元素并单击它。