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. Preferably, I would like to be able to access them by src but not sure if this is possible. 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"]
). Good relative XPath
could match required element on several pages
If you want to match target img
with src
attribute value, then you can use following 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
If you want to access using src
attribute then
Using CSSSelector -
img[src='/images/Overground.png']
using 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 -
//span[2]/img
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.