[英]In selenium, how do I access the second image element with the same class name, without using XPath?
I am making some reusable methods that locate image elements within a page. 我正在做一些可重用的方法来定位页面中的图像元素。 I cannot locate by XPath as the XPath will be different on each one of the pages. 我无法通过XPath进行定位,因为每个页面上的XPath都会不同。 Preferably, I would like to be able to access them by src but not sure if this is possible. 最好是,我希望能够通过src访问它们,但不确定是否可行。 C#. C#。 The code below shows two image elements. 下面的代码显示了两个图像元素。 I am trying to access the second. 我正在尝试访问第二个。
<span id="tube"> <img class="mode-icon" title="Train: Tube" height="42" alt="Tube" src="/images/Tube.png"> </span>
<span id="Overground"> <img class="mode-icon" title="Train: Overground" height="42" alt="Overground" src="/images/Overground.png"> </span>
First of all you should differentiate absolute XPath
(fixed, eg html/div/div/.../div/img
) and relative XPath
(flexible, eg //div/img[@id="some_img_id"]
). 首先,您应该区分绝对 XPath
(固定,例如html/div/div/.../div/img
)和相对 XPath
(灵活,例如//div/img[@id="some_img_id"]
)。 Good relative XPath
could match required element on several pages 良好的相对XPath
可以与多个页面上的必需元素匹配
If you want to match target img
with src
attribute value, then you can use following XPath
: 如果要将目标img
与src
属性值匹配,则可以使用以下XPath
:
string imgSrc = "/images/Overground.png";
string imgXpath = String.Format("//img[@src = {0}]", imgSrc);
Same XPath
expression you can use for any value of imgSrc
可用于imgSrc
任何值的相同XPath
表达式
If you want to access using src
attribute then 如果要使用src
属性进行访问,则
Using CSSSelector - 使用CSSSelector-
img[src='/images/Overground.png']
using XPath 使用XPath
//img[@src='/images/Overground.png']
If it is fix that you have only 2 image tag in you page then you can use indexing as well - 如果您的页面中只有2个图片标签是固定的,那么您也可以使用索引-
//span[2]/img
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.