python - 使用selenium从元素获取src

标签 python selenium xpath css-selectors webdriverwait

我正在尝试以字符串形式获取元素的 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 检查元素中的元素的样子:

element

最佳答案

看来你已经很接近了。提取 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/

相关文章:

Java Selenium WebDriver 与 Yandex

python - lxml - 如何获取 HtmlElement 的 xpath?

python - Python/GAE社交网络/CMS?

python - 如何在 pytest 中进行自定义比较?

python - Python 中的约束最小二乘估计

java - 使用 Selenium 循环链接

java - 在以下 HTML 的 Selenium webdriver 中出现 "Element is not currently visible and so may not be interacted with"错误

iphone - GDataXML/Libxml2 XPath concat 不起作用

xpath 获取所有子文本

python - 当其中一个元素是 Python 字典时,向 MySQL 表中插入一行