Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

So the following code has ID's for each button but they are dynamic every refresh and I've tried using maleBtn = driver.find_element_by_xpath('//button[text()="Male"]').click() however that doesn't seem to select or click the button.

    <div id="759f1410-6451-4e18-8ef7-641692381f54" class="gender-buttons gender component">
  <div class="shim"></div>
  <div class="error"></div>
  <label for="27be9dfd-67f6-4fc1-8e7d-cf18edad0b6d">Gender</label>

  <input type="hidden" id="27be9dfd-67f6-4fc1-8e7d-cf18edad0b6d" value="" name="gender" data-componentname="gender">

  <ul data-componentname="gender">
    
      <li id="c5348cb4-3dd3-4841-8bec-d41523d16d11" class="">
        <input type="button">
        <span>Male</span>
      </li>
    
      <li id="fd7b0bd9-0c59-41be-8b5c-fbbe1e97ba9b" class="">
        <input type="button">
        <span>Female</span>
      </li>
    
  </ul>
  <div class="tip">Please select a preference.</div>
</div>

Any thoughts of making this work?

question from:https://stackoverflow.com/questions/65546174/how-can-selenium-click-a-button-with-a-dynamic-id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
138 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you want to click the preceding input tag of male.

//ul[@data-componentname='gender']//span[text()='Male']/preceding::input[@type='button']

Got the element before but it ran into an overlapping element so I just invoked click directly to the element. Also if you haven't use Webdriver waits to allow the page to load the element properly.

Complete Code:

driver.get('https://www.nike.com/ca/register')
wait = WebDriverWait(driver, 10)
maleBtn = wait.until(EC.element_to_be_clickable((By.XPATH, "//ul[@data-componentname='gender']//span[text()='Male']/preceding::input[@type='button']")))
driver.execute_script("arguments[0].click();", maleBtn)

Imports

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

Outputs

Clicked Element


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...