我需要使用 python 中的 selenium 來驗證圖片是否顯示在頁面上。
例如,讓我們檢查 https://openweathermap.org/ 頁面左上角的標誌。
我使用 execute_script ,我的程式碼是:
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))
我得到了這個結果:
True False 431
為什麼 typeof argument[0].naturalWidth>0 是 False,而 arguments[0].naturalWidth 是 431?並且圖像在頁面上正確呈現。
更新:正確的程式碼是:
print(driver.execute_script("return (arguments[0].naturalWidth>0);", image))
typeof運算子優先於>。