Selenium Python get_attribute("src") returns None, 即使有一个 "src" 属性

Selenium Python get_attribute("src") returns None, eventhough there is a "src" attribute

Selenium Python get_attribute("src") returns None,尽管有一个“src”属性

代码试验:

link = f"https://duckduckgo.com/?q={searchtext}&iax=images&ia=images"
driver = webdriver.Firefox()
driver.get(link)
time.sleep(2)
tabbutton = driver.find_element(By.CSS_SELECTOR, "div.tile:nth-child(3)")
webdriver.ActionChains(driver).click(tabbutton).perform()
imagelink = driver.find_element(By.CSS_SELECTOR, "div.detail__pane:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > a:nth-child(1) > img:nth-child(3)")
src = imagelink.get_attribute("src")
print(src)

它总是打印“None”并且所有其他属性都有效。 html 是:

<img style="width: 218.333px; height: 262px; display: block;" alt="Flower Blume Pflanze Lila Gelb - ZoPix.NET" class="detail__media__img-highres  js-detail-img  js-detail-img-high" src="//external-content.duckduckgo.com/iu/?u=http%3A%2F%2Fen.zopix.net%2Fimage_upload%2F138342-flower-blume-pflanze-lila.JPG&amp;f=1&amp;nofb=1">

要打印 src 属性的值,您需要引入 for the and you can use either of the following :

  • 使用CSS_SELECTOR:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "img.detail__media__img-highres[alt^='Flower Blume Pflanze Lila Gelb - ZoPix']"))).get_attribute("src"))
    
  • 使用 XPATH:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//img[@class='detail__media__img-highres  js-detail-img  js-detail-img-high' and @alt='Flower Blume Pflanze Lila Gelb - ZoPix.NET']"))).get_attribute("src"))
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC