1
votes

I'm trying to get a background image url using xpath .

my xpath expression so far:

//div[@class='Header']/div[@class='Header-jpeg']

which points to the div that has the background-image but from there no idea how to get the img url, probably something in @style but no luck so far.

Css of that div:

div.Header-jpeg {
    position: absolute;
    z-index: -1;
    top: 0;
    left: 0;
    width: 874px;
    height: 94px;
    background-image: url('images/Header.jpg');
    background-repeat: no-repeat;
    background-position: center center;
}

and a real example ca be found here: http://www.landenkompas.nl/

2

2 Answers

2
votes

Something like this should work:

substring-before(substring-after(//div[@class='Header']/div[@class='Header-jpeg']/@style, 'background-image: url('), ')')

However, be warned that if you're using Java XPath it will only get the first element it finds. If you have multiple, you'll need to find another way to aggregate all the values.

0
votes

Assuming you are using selenium, you need to get a value of the CSS property.

In Java:

WebElement element = driver.findElement(By.xpath("//div[@class='Header']/div[@class='Header-jpeg']"));
element.getCssValue("background-image");

In Python:

element = driver.find_element_by_xpath("//div[@class='Header']/div[@class='Header-jpeg']")
element.value_of_css_property("background-image")