I'm trying to select an image element using its style selector. I wrote the line of code in Python but I'm having problems translating it to JavaScript. Here's my attempt so far. Please note the python code works. It's the js I'm having problems with.
if driver.find_element_by_css_selector("img[style='object-fit: cover;']") is not None:
download_url = driver.find_element_by_css_selector("img[style='object-fit: cover;']").get_attribute('src')
And here is my js attempt.
let imageArr = []
for(let post of posts) {
await page.goto(post)
await page.waitForTimeout(6000)
if (await page.type("img[style='object-fit: cover;']") !== null) {
const image = await page.evaluate(() => {
document.querySelectorAll("img[style='object-fit: cover;']").forEach(img => {
let imageUrl = img.getAttribute('src');
imageArr.push(imageUrl)
})
})
}
}
I think you need to use the * CSS attribute selector, from MDN:
[attr*=value] - Represents elements with an attribute name of attr whose value contains at least one occurrence of value within the string.
So for your Javascript code, I believe this will work:
let imageArr = []
for(let post of posts) {
await page.goto(post)
await page.waitForTimeout(6000)
if (await page.type("img[style*='object-fit: cover;']") !== null) {
const image = await page.evaluate(() => {
document.querySelectorAll("img[style*='object-fit: cover;']").forEach(img => {
let imageUrl = img.getAttribute('src');
imageArr.push(imageUrl)
})
})
}
}
This will select all img elements that have at least one occurrence of object-fit: cover; within the string.