我正在尝试以字符串形式获取元素的 src。
我使用find_element_by_xpath()
来查找元素。我可以使用 element.get_attribute("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
无
这是 chrome 检查元素中的元素的样子:
最佳答案
看来你已经很接近了。提取 src 属性 作为元素 JavaScript启用的元素,您必须为 visibility_of_element_ located()
引发WebDriverWait,并且您可以使用以下任一 Locator Strategies :
使用
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
关于python - 使用selenium从元素获取src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56928281/