Selenium:基于标签文本点击动态值单选按钮的方案
动态定位并点击“Certification Exam”单选按钮
我正在处理一个包含20多个单选按钮的网页,需要通过Python脚本点击标签文本为“Certification Exam”的特定单选按钮,但遇到了定位难题。目标按钮的HTML结构如下:
<li class="list-group-item"> <label> <input type="radio" name="student[progress]" value="27162" checked=""> Certification Exam </label> </li>
该按钮的value属性会随用户选择的地区(州/省)动态变化,比如亚利桑那州对应27162,阿肯色州对应28156。目前只有硬编码value的代码能稳定运行,但仅适用于单个地区:
try: certification_exam_radio = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, 'input[type="radio"][value="27162"]')) ) driver.execute_script("arguments[0].scrollIntoView(true);", certification_exam_radio) driver.execute_script("arguments[0].click();", certification_exam_radio) except Exception as e: print(f"Error while clicking on the 'Certification Exam' radio button: {e}")
我尝试了6种动态定位方法均未成功,其中一种尝试的代码如下:
def click_certification_exam_radio(driver, exam_text="Certification Exam"): try: certification_exam_radio = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, f"//label[contains(text(), '{exam_text}')]/input[@type='radio']")) ) driver.execute_script("arguments[0].scrollIntoView(true);", certification_exam_radio) driver.execute_script("arguments[0].click();", certification_exam_radio) except Exception as e: print(f"Error while clicking on the 'Certification Exam' radio button: {e}") # Usage: click_certification_exam_radio(driver)
注:手动点击标签文本也可触发单选按钮,且目标按钮通常为最后一个。
经过尝试,最终找到基于标签文本定位的通用可行方案,代码如下:
selector = "//input[@type='radio']" print("Attempting to locate all radio buttons on the page...") try: radio_buttons = WebDriverWait(driver, 10).until( EC.presence_of_all_elements_located((By.XPATH, selector)) ) print(f"Found {len(radio_buttons)} radio buttons!") for idx, radio in enumerate(radio_buttons, start=1): label = driver.execute_script("return arguments[0].parentNode.textContent;", radio).strip() value = radio.get_attribute("value") print(f"Radio Button {idx}:") print(f" Value = {value}") print(f" Label = {label}") if "Exam" in label and "Practice" not in label: print("Found the target radio button. Attempting to click using JavaScript...") driver.execute_script("arguments[0].click();", radio) break save_changes_button = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, 'button.btn.btn-success')) ) driver.execute_script("arguments[0].scrollIntoView(true);", save_changes_button) time.sleep(1) driver.execute_script("arguments[0].click();", save_changes_button) except Exception as e: print(f"Error during operation: {e}")
内容的提问来源于stack exchange,提问作者AtFirstYouTry
相关产品推荐
相关产品推荐

