简体   繁体   中英

Python selenium click a button without id

i have this code

<a href="#" class="button expanded vote" style="background: rgb(51, 204, 102) none repeat scroll 0% 0%; border-radius: 5px;" onclick="Poll.sendAnswer("Programn2015","Answer1","Answer2")">Vote</a>

what could i do? there are other buttons on the page with the same class etc, the only variables are

"Answer1","Answer2"

To click on the link with text as Vote you can use either of the following solutions:

  • css_selector :

     driver.find_element_by_css_selector("a.button.expanded.vote[onclick*='Answer1'][onclick*='Answer2']").click()
  • xpath :

     driver.find_element_by_xpath("//a[@class='button expanded vote' and contains(.,'Vote')][contains(@onclick,'Answer1') and contains(@onclick,'Answer2')]").click()

Update

Induce WebDriverWait for the desired element to be clickable as follows:

  • css_selector :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.button.expanded.vote[onclick*='Answer1'][onclick*='Answer2']"))).click()
  • xpath :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='button expanded vote' and contains(.,'Vote')][contains(@onclick,'Answer1') and contains(@onclick,'Answer2')]"))).click()

Note : You have to add the following imports :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM