【问题标题】:Unable to locate text element in aria-label with the XPath expression无法使用 XPath 表达式在 aria-label 中找到文本元素
【发布时间】:2019-06-12 19:52:51
【问题描述】:

我正在尝试自动化填写登录后出现的网站安全问题的过程。从我已经回答的 6 个问题中随机提出两个问题。

我尝试识别在“aria-label”元素中找到的特定安全问题的每个 Xpath 选项都返回 NoSuchElementException

我在谷歌兔子洞里尝试了很多方法,包括:

#First Attempt
question_1=browser.find_element_by_xpath('//div[@label="name of first employer?"]')

#Second Attempt 
question_1=browser.find_element_by_xpath('//form[@label="name of first employer?"]/label[text()="name of first employer?"]')

我为以下两个安全问题添加了已检查元素的 html:

<input type="password" name="first_security_question" aria-label="Unique pin #4" value="">

<input type="password" name="second_security_question" aria-label="Model of first car?" value="">

我希望识别 aria-label 中的特定问题,以便我可以发送适当的键来填写表单问题,但我得到的只是NoSuchElementException

【问题讨论】:

    标签: python selenium nosuchelementexception


    【解决方案1】:

    如果您想获得问题,请执行以下操作。

    # get the question 1 element
    questionEle=browser.find_element_by_xpath("//input[@name='first_security_question']")
    # get the question
    question_1 = questionEle.get_attribute("aria-label")
    

    然后获取问题的答案并将输入发送到问题。

    【讨论】:

    • 如果您认为问题已解决,请点击左侧我的答案中的否决按钮下方的神圣复选标记来接受答案。
    • 我尝试了你的建议,但得到了同样的异常错误“NoSuchElementException”
    • 更新的建议无效。我的代码在这里:drive.google.com/file/d/1Zqb2MrimYb_gV2YmyBEc2AM8IKxNdHWO/…
    • 您必须更改questionEle 行代码以匹配我的答案。您当前方法的问题是,当 name of first employer? 不属于 2 个问题(共 6 个)时,您将获得 NoSuchElement 异常。这就是为什么您应该通过基于name 获取aria-label 来回答问题的原因