使用find_elements后调用find_element报'list'对象无该属性错误求助
问题解决:'list' object has no attribute 'find_element'
错误根源
find_elements()方法返回的是WebElement对象的列表,而列表类型不存在find_element()方法——你直接对列表调用这个方法,自然会触发报错。
你的尝试问题分析
- 第一种方法:
WebDriverWait只能接收WebDriver或单个WebElement实例,不能传入列表,所以等待逻辑完全无效。 - 第二种方法:循环里依然对
game_report(列表)调用find_element,而非对循环迭代出的单个group_entry元素调用,逻辑错误。 - 第三种方法:先对列表调用
find_element(本身就不符合语法),再取索引,完全是错误的用法。
正确解决方案
方案1:获取第一个分组下的目标元素
如果只需要第一个分组里的trn-gamereport-list__group-entries元素,直接从列表中取出单个元素再调用find_element:
driver = webdriver.Chrome() url = "https://destinytracker.com/destiny-2/profile/psn/4611686018440125811/matches?mode=crucible" driver.get(url) crucible_content = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.trn-gamereport-list.trn-gamereport-list--compact"))) game_report = crucible_content.find_elements(By.CLASS_NAME, "trn-gamereport-list__group") # 取出列表中的第一个分组元素 first_group = game_report[0] # 对单个元素调用find_element group_entry = first_group.find_element(By.CLASS_NAME, "trn-gamereport-list__group-entries")
方案2:遍历所有分组获取目标元素
如果需要处理每个分组下的trn-gamereport-list__group-entries,用循环遍历列表中的每个元素:
driver = webdriver.Chrome() url = "https://destinytracker.com/destiny-2/profile/psn/4611686018440125811/matches?mode=crucible" driver.get(url) crucible_content = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.trn-gamereport-list.trn-gamereport-list--compact"))) game_report = crucible_content.find_elements(By.CLASS_NAME, "trn-gamereport-list__group") # 遍历每个分组元素 for group in game_report: group_entry = group.find_element(By.CLASS_NAME, "trn-gamereport-list__group-entries") # 这里添加对group_entry的处理逻辑,比如提取数据 print(group_entry.get_attribute("innerHTML"))
方案3:直接用精确选择器一步定位
可以跳过层级查找,直接用CSS选择器定位所有目标元素,简化代码:
driver = webdriver.Chrome() url = "https://destinytracker.com/destiny-2/profile/psn/4611686018440125811/matches?mode=crucible" driver.get(url) # 直接定位所有分组下的entries元素 group_entries = WebDriverWait(driver, 20).until( EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div.trn-gamereport-list__group .trn-gamereport-list__group-entries")) ) # 取第一个元素:group_entries[0] # 遍历所有元素: for entry in group_entries: print(entry.text)
关键注意点
- 区分
find_element()(返回单个匹配元素,无匹配则报错)和find_elements()(返回所有匹配元素的列表,无匹配则返回空列表) - 使用
WebDriverWait时,必须传入WebDriver实例或单个WebElement对象,不能传入列表 - 优先使用更精确的CSS/XPath选择器,减少多层级查找的复杂度
内容的提问来源于stack exchange,提问作者internshiphopeful
相关产品推荐
相关产品推荐

