Selenium Python运行报错AttributeError:'str'对象无get_attribute属性问题求助
错误根源
两次实例化类时传入的video_xpath参数类型不匹配:
- 第一次实例化
Like类时,传入的like_path是driver.find_element_by_xpath()返回的Selenium WebElement对象,支持get_attribute、click等元素操作方法 - 第二次实例化
Refiq子类时,直接传入了字符串格式的XPath路径,没有调用元素查找接口,所以self.video_xpath本质是字符串,调用get_attribute时自然触发属性不存在的异常
修复方案
方案1:保持调用逻辑统一,实例化前先查找元素
和第一次调用Like类的逻辑对齐,调用Refiq前先执行元素查找,再把WebElement对象传入:
# 修正前错误写法:直接传XPath字符串 # refq_unfrefiq=Refiq(video_xpath="//w-creation-detail-popup//li[2]//a[1]",like_refiq="refiq") # 修正后写法 refiq_path = driver.find_element_by_xpath("//w-creation-detail-popup//li[2]//a[1]") refq_unfrefiq = Refiq(video_xpath=refiq_path, like_refiq="refiq") refq_unfrefiq.like_dislike()
方案2:优化类结构,支持直接传入XPath字符串
如果需要兼容直接传XPath字符串的调用方式,可以修改类的初始化逻辑,传入driver后自动完成元素查找:
class Like(): # 初始化方法新增driver入参 def __init__(self, driver, video_xpath, like_refiq): self.driver = driver # 自动判断参数类型,兼容WebElement和XPath字符串两种传参 if isinstance(video_xpath, str): self.video_element = self.driver.find_element_by_xpath(video_xpath) else: self.video_element = video_xpath self.like_refiq = like_refiq def like_dislike(self): like = self.video_element time.sleep(5) class_status = like.get_attribute("class") if class_status == "selected": like.click() time.sleep(3) alredy_count = like.text return print(f"creation un{alredy_count} {self.like_refiq} count") elif class_status == "": like.click() time.sleep(3) non_count = like.text return print(f"creation {non_count} {self.like_refiq} count") else: assert False class Refiq(Like): pass
修改后两种传参方式都可以正常运行:
# 传已经查找好的WebElement对象 like_path = driver.find_element_by_xpath("//w-creation-detail-popup//li[1]//a[1]") Like_dislike = Like(driver, video_xpath=like_path, like_refiq="like") Like_dislike.like_dislike() # 直接传XPath字符串 refq_unfrefiq = Refiq(driver, video_xpath="//w-creation-detail-popup//li[2]//a[1]", like_refiq="refiq") refq_unfrefiq.like_dislike()
内容的提问来源于stack exchange,提问作者Nabeel Ahmad
相关产品推荐
相关产品推荐

