search

Home  >  Q&A  >  body text

Selenium + Python - inspect image via execute_script

I need to verify that an image is displayed on the page using selenium in python. For example, let's examine the logo in the upper left corner of the https://openweathermap.org/ page. I use execute_script and my code is:

def test_image(driver):
    driver.get('https://openweathermap.org/')
    time.sleep(10)
    image = driver.find_element(By.CSS_SELECTOR, "#first-level-nav > li.logo > a > img")
    print(image)
    print(driver.execute_script("return (typeof arguments[0].naturalWidth!=\"undefined\");", image))
    print(driver.execute_script("return (typeof arguments[0].naturalWidth>0);", image))
    print(driver.execute_script("return (arguments[0].naturalWidth);", image))

I got this result:

True
False
431

Why typeof argument[0].naturalWidth>0 is False, while arguments[0].naturalWidth is 431? And the image renders correctly on the page.

Update: The correct code is:

print(driver.execute_script("return (arguments[0].naturalWidth>0);", image))

P粉899950720P粉899950720271 days ago590

reply all(1)I'll reply

  • P粉765570115

    P粉7655701152024-04-04 00:48:58

    The

    typeof operator takes precedence over >.

    typeof 431     === "number"
    "number"   > 0 === false
    typeof 431 > 0 === false

    reply
    0
  • Cancelreply