首页 > 解决方案 > 无法使用 Python Selenium 在跨度类中定位元素

问题描述

我一直在努力在跨度类中找到一个元素。该元素是一个单选标记按钮。这是html:

<span class="radio-container" for="searchType_2">
<input class="form-check-input" type="radio" name="searchType" id="searchType_2" value="cidade">
<span class="radio-checkmark">
::after

由于上面的类不是唯一的,我尝试了以下方法:

dropdown_menu = self.driver.find_element_by_css_selector('[for="searchType_2"] .radio-checkmark')

当我使用上面的 CSS 选择器进行检查和搜索时,它可以工作。它显示为 1 of 1。但是当我运行代码时,出现以下异常:

no such element: Unable to locate element: {"method":"css selector","selector":"[for="searchType_2"] .radio-checkmark"}
(Session info: chrome=92.0.4515.107

谢谢

标签: pythonhtmlcssselenium

解决方案


您尝试访问的元素位于 iframe 内。在访问其中的任何元素之前,您需要切换到 iframe

driver.switch_to_frame(driver.find_element_by_xpath("//iframe[@class='cz-map-frame']"))
driver.find_element_by_xpath("//input[@id='searchType_2']//following::span[@class='radio-checkmark'][1]").click();

推荐阅读