在Selenium Webdriver Python中存储图像标题文本
我正在用Python进行网页抓取,想要保存图片的标题(就是当你把鼠标放在图片上时出现的文字)。这是我目前的尝试:
from selenium import webdriver
driver= webdriver
imageTitle= driver.find_elements_by_xpath("//td[2]/div/img").title.encode('utf8')
当我运行这段代码时,出现了一个错误:AttributeError: 'list' object has no attribute 'title'
。我也试过:
imageTitle= driver.find_elements_by_xpath("//td[2]/div/img").text.encode('utf8')
这段代码变成了另一个错误:AttributeError: 'list' object has no attribute 'text'
我知道这个问题应该比较简单解决,但我完全不知道该怎么做,感谢大家的帮助。
1 个回答
2
因为你使用的是 find_elements_by_xpath
,而不是 find_element_by_xpath
,注意前者是复数 elements
,而后者是单数 element
。
driver.find_elements_by_xpath
会返回一个元素的列表,而 text
是单个元素的一个属性。你要么使用 find_element_by_xpath
,要么对 find_elements_by_xpath
的结果进行索引。
AttributeError: 'list' object has no attribute 'text'
这条错误信息已经很清楚地告诉你了这一点。
另外,你提到的标题是元素的一个属性,所以需要这样做:
imageTitle= driver.find_element_by_xpath("//td[2]/div/img").get_attribute("title")