使用 selenium 从元素获取 src

Getting src from element using selenium

我正在尝试获取一个元素的 src 作为字符串。

我用 find_element_by_xpath() 找到了元素。我可以使用 element.get_attribute("class") 获取 class 但无法通过这种方式获取 src

我的代码片段:

image = driver.find_element_by_xpath('//*[@id="irc_cc"]/div[2]/div[1]/div[2]/div[1]/a/img')
print(image.get_attribute("class"))
print(image.get_attribute("src"))

这是我的终端的结果:

irc_mi None

这是 chrome 检查元素中的元素的样子:

看来你很接近。提取 src 属性 因为元素是 JavaScript enabled element you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following :

  • 使用CSS_SELECTOR:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "img.irc_mi[alt='Image result for snowman']"))).get_attribute("src"))
    
  • 使用XPATH:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//img[@class='irc_mi' and @alt='Image result for snowman']"))).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