Selenium代码报错'list' object has no attribute 'text',无法获取搜索结果摘要
问题解决:'list' object has no attribute 'text'
错误原因很明确:你用了find_elements()(复数形式),这个方法会返回一个元素列表,而列表类型没有text属性。从你的需求来看,每篇文章(article)下应该只有一个摘要(entry-summary),所以应该用单数形式的find_element()来获取单个元素。
修正后的代码如下:
driver = webdriver.Chrome(path) driver.get("https://techwithtim.net") search = driver.find_element(By.NAME, "s") search.send_keys("test") search.send_keys(Keys.RETURN) try: main = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "main")) ) articles = main.find_elements(By.TAG_NAME, "article") for article in articles: # 改用find_element单数形式,获取单个元素 header = article.find_element(By.CLASS_NAME, "entry-summary") print(header.text) finally: driver.quit()
如果遇到单篇文章下有多个entry-summary元素的情况,你可以遍历返回的列表来逐个获取文本:
headers = article.find_elements(By.CLASS_NAME, "entry-summary") for h in headers: print(h.text)
内容的提问来源于stack exchange,提问作者Jaevapple
相关产品推荐
相关产品推荐

