【问题标题】:How do I use python and selenium to find the element of a radio button using the text related to the radio button?如何使用 python 和 selenium 使用与单选按钮相关的文本来查找单选按钮的元素?
【发布时间】:2017-11-02 10:22:33
【问题描述】:

我正在尝试编写一个代码,我可以用它来自动化我每年必须完成的培训课程。年复一年地使用相同的材​​料和相同的培训,所以我想为什么不自动化它。

我被卡住的部分是单击一个单选按钮。我可以通过 xpath 使用 find 元素来选择单选按钮,但由于答案是随机的,我想通过与单选按钮相关的文本来查找元素。我曾尝试使用find_element_by_partial_link 并没有运气,我也可能做错了。这是我尝试过的:

test = browser.find_element_by_partial_link_text('Is this achievable?').

这是我要访问的元素:

<label for="q1789110:1_answer0" style="background-color: rgb(234, 114, 0);" id="yui_3_17_2_3_1509578998475_118">Is this achievable?</label>

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 可以分享网页的链接吗?
  • 给我们整个 HTML 页面。
  • 我认为labelid 是动态的,每个问题都会发生变化。 Is this achievable? 将是所有 labels 的通用文本。因此,为了查找/定位/搜索与确切问题相关的Is this achievable? 标签,您可能需要共享QuestionHTML 以及LabelsLabels
  • 是的,我很抱歉发送完整的 URL。通过发送完整的 URL,它需要你长它。这是一个问题吗?我是stackoverflow的新手,很抱歉造成混乱。

标签: python selenium automation


【解决方案1】:

如果你的 html 代码是这样的

<form action="/action_page.php">
  <label for="male">Male</label>
  <input type="radio" name="gender" id="male" value="male"><br>
  <label for="female">Female</label>
  <input type="radio" name="gender" id="female" value="female"><br>
  <label for="other">Other</label>
  <input type="radio" name="gender" id="other" value="other"><br><br>
  <input type="submit" value="Submit">
</form>

您可以先使用 xpath 以使用文本查找标签节点,然后获取它的 'for' 属性:

for_attr = driver.find_element_by_xpath("//label[text()='Male']").get_attribute("for")

然后你可以找到输入元素以便点击它:

通过 xpath

driver.find_element_by_xpath("//input[@type='radio' and @id='%s']" % (for_attr)).click()

或通过 id

driver.find_element_by_id(for_attr).click()

The for attribute of the label tag should be equal to the id attribute of the related element to bind them together.

【讨论】:

    【解决方案2】:

    如果这是你的元素:

    <script>
    function myFunction() {
        alert("Hello!")
    }
    </script>
    
    
    <label for="q1789110:1_answer0" style="background-color: rgb(234, 114, 0);" id="yui_3_17_2_3_1509578998475_118" onclick="myFunction()">Is this achievable?</label>
    

    如果你想使用xpath,你可以使用"text()"的and条件:

    driver.find_element_by_xpath("//label[@id='yui_3_17_2_3_1509578998475_118' and text()='Is this achievable?']").click()
    

    编辑

    如果 id 发生变化,你可以检查文本值:

    driver.find_element_by_xpath("//label[text()='Is this achievable?']").click()
    

    【讨论】:

    • 我没有尝试过任何东西,包括“text()=",但我使用 Id 的问题是每次页面加载时元素的 ID 都会发生变化并导致问题。
    • @JPython 好的,如果 id 发生变化,您可以使用“text()”值来识别元素
    猜你喜欢
    • 2015-07-22
    • 2018-08-04
    • 2018-04-30
    • 2017-08-02
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多