【问题标题】:XPath to select element without a unique id attribute?XPath 选择没有唯一 id 属性的元素?
【发布时间】:2017-11-27 05:48:28
【问题描述】:

我正在使用 Selenium 并测试新事物,我试图制作一个程序来单击 Yt 上的 Like 按钮,但 XPath 是错误的,我不知道如何获得正确的 XPath,谁能告诉我一种获取元素“真实”Xpath 的方法?

chrome.FindElementByXPath("//*[@id='button']").Click();

使用此 XPath 的按钮不止一个,这是肯定的,但我想知道如何指定我想要的按钮。

<yt-icon-button id="button" class="style-scope ytd-toggle-button-renderer style-text" aria-pressed="false"><button id="button" class="style-scope yt-icon-button" aria-label="Ich mag das Video (wie 8.019 andere auch)"><yt-icon class="style-scope ytd-toggle-button-renderer"><svg viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" focusable="false" class="style-scope yt-icon" style="pointer-events: none; display: block; width: 100%; height: 100%;"><g class="style-scope yt-icon">
        <path d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-1.91l-.01-.01L23 10z" class="style-scope yt-icon"></path>
      </g></svg>
    
  </yt-icon></button></yt-icon-button>

【问题讨论】:

  • 有一个 firefox Selenium 插件,可以告诉你任何元素的最简单可靠的 xpath(或者至少,你可以只记录点击它的动作)。
  • 你能发布xml吗?

标签: c# html xml selenium xpath


【解决方案1】:
//*[@id="button"]

使用此 XPath 的按钮不止一个,这是肯定的,但我想知道如何指定我想要的按钮。

有很多方法可以使上述 XPath 更具选择性。哪种效果最好取决于您忽略向我们展示的目标标记。

以下是一些提高 XPath 特异性的通用想法:

  • 指定遗产/full/path/to/element[@id="button"]
  • 添加另一个属性//*[@id="button" and @class="UniqueClassName"]
  • 使用索引//*[@id="button"][2]
  • 利用标签//*[@id="button" and preceding-sibling::span="Age:"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2012-11-30
    • 2023-03-20
    • 2010-09-18
    相关资源
    最近更新 更多