Python Selenium 获取图像标题

Python Selenium get image title

我尝试提取由 xpath 定位的元素的图像标题:

<div class="c-label"><img title="title of the image" src="https://test.com/images/12345.png" class="c-label__image"> <span title="something" class="c-label__text">something</span></div>

使用此代码,我得到了元素的 div class (c-label):

xp = "/html/body/div[2]/div[1]/div[2]/div/div/div[2]/div/div/div/div[1]/div[1]/div/div[2]/div/div/div/div[2]/div/div[2]/div[1]/div"

element = driver.find_element_by_xpath(xp)

content = element.get_attribute("class")

print(content)

现在我想获取 img 标题,但是 get_attribute("title")get_attribute("img title") 不起作用。

您必须定位 image 元素才能获得标题。 使用下面 xpathcss selector.

XPATH:

print(driver.find_element_by_xpath("//div[@class='c-label']/img[@class='c-label__image']").get_attribute("title"))

CSS 选择器:

print(driver.find_element_by_css_selector("div.c-label > img.c-label__image").get_attribute("title"))