所以我一直在 Python 中使用 Selenium。我完成了我的代码(当时有效),但突然它选择不再工作。 再具体一点: 如果我尝试:
driver.find_element_by_id("leasingtrue").click()
它返回给我错误:
selenium.common.exceptions.ElementNotInteractableException: Message: Element <input id="leasingfalse" name="IsLeasing" type="radio"> could not be scrolled into view
另一方面,如果我通过 XPath 找到该元素,它就会按预期工作。 该错误仅在类型为“radio”时发生,但在每个类型上都一致。
由于完整的代码大约有 600 行长,我不打算将其中的每一行都更改为 XPath。 另一条相关信息: 因为我正在使用 PyCharm,所以我可以恢复到以前肯定有效的版本。 但现在,它也给了我同样的错误。有谁知道这个错误可能与什么有关?
我正在抓取的网站是:https://www.comparis.ch/autoversicherung/berechnen?carmake=41 。 我正在使用 Python 2.7 和 Selenium 3.8 相关的 HTML 是:
<div class="item-selectable xsmall-6 columns">
<input data-val="true" data-val-required="Bitte wählen Sie eine Antwort aus." data-vertical-alignment="middle" id="leasingtrue" name="IsLeasing" type="radio" value="true" aria-required="true" aria-invalid="false" aria-describedby="IsLeasing-error">
<label for="leasingtrue">Ja</label>
</div>
最佳答案
因为您操作的元素不是单选按钮,而是切换按钮,由CSS + 单选按钮+标签
实现。
从用户界面中,我们可以看到单选按钮被标签覆盖,因此您无法单击单选按钮来选择切换按钮,而是单击标签来执行此操作。
driver.find_element_by_css_selector("input#leasingtrue + label").click();
关于python - Selenium find element_by_id 不适用于单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48746229/