猿问

错误消息:无法定位元素。可能是什么问题?

当使用 selenium 使用 Xpath 查找元素标签时,它使用从 chrome 为该元素复制的 xpath 工作,这是为了测试它是否工作。由于每次打开网页时 id 元素都会更改,我知道这会导致我的 Web 自动化程序出错,现在从同一个标签中,我正在使用 class 元素,因为每次打开网页时它都不会改变,但是 Selenium根本找不到那个元素。当我将 xpath 中的元素更改为具有来自 xpath 的相对名称的类时,我最初是从 webbroswer 复制和测试的。可能是什么问题?


这是我想要访问的 html 源代码和 Xpath 的示例:


<div class="popover fade right in" role="tooltip" id="popover784483" style="top: -9px; left: 328.5px; display: block;">

    <div class="arrow" style="top: 88.9423%;"></div>

    <h3 class="popover-title">

        <font style="vertical-align: inherit;">

            <font style="vertical-align: inherit;">Member details</font>

        </font>

    </h3>

    <div class="popover-content">

        <img class="center-block" src="http://api.vdarts.net:8080/picture/portrait/default.png" style="max-width:200px;height:auto;">

        <hr>

        <font style="vertical-align: inherit;">

            <font style="vertical-align: inherit;">Account: CapitainJack </font>

Xpath 最初使用但 id 更改:


//*[@id="popover784483"]/div[2]/font[1]/font

要使用的 Xpath:


//*[@class="popover fade right in"]/div[2]/font[1]/font


慕雪6442864
浏览 216回答 2
2回答

智慧大石

有很多方法可以解决这个问题。您可以匹配部分文本内容 Xpath,如//*[contains(text(),&nbsp;'Account')]您可以使用 Img 标签和以下字体(//img//following::font)[2]

回首忆惘然

我建议您改用CSS选择器。复合类名是指一个元素具有多个用空格分隔的类。例如<div class="class1 class2 class3"></div>如果要选择具有所有 3 个类(以任何顺序)的元素,可以使用:element&nbsp;=&nbsp;driver.find_element_by_css_selector(".class1.class2.class3")如果您想使用 XPath,我发现以下方法有效(使用与上面相同的示例):browser.find_elements_by_xpath("//*[contains(concat('&nbsp;',@class,'&nbsp;'),'&nbsp;class1&nbsp;')&nbsp;and&nbsp;contains(concat('&nbsp;',@class,'&nbsp;'),'&nbsp;class2&nbsp;')&nbsp;and&nbsp;contains(concat('&nbsp;',@class,'&nbsp;'),'&nbsp;class3&nbsp;')]")注意:您可以使用不同的布尔运算符来过滤掉某些类名(例如 'and' 'and not' 等)
随时随地看视频慕课网APP

相关分类

Python
我要回答