You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium爬虫输出为HTML代码,获取文本时触发AttributeError求助

解决Selenium爬取时AttributeError: 'list' object has no attribute 'text'的问题

问题根源

你使用的find_elements()方法会返回匹配到的元素列表,而非单个WebElement对象,列表类型没有.text属性,这就是报错的直接原因。不管是代码里的article.find_elements(By.CLASS_NAME, "entry-summary"),还是错误栈里的posted-on,只要用了复数形式的find_elements,得到的都是元素集合,无法直接调用.text。

解决方案

根据每个article下entry-summary元素的数量,选择对应的处理方式:

情况1:每个article下只有一个entry-summary元素

改用单数形式的find_element()获取单个元素,再调用.text提取文本:

driver.get("https://www.techwithtim.net/")

search = driver.find_element("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()

情况2:每个article下有多个entry-summary元素

遍历find_elements()返回的元素列表,逐个提取文本:

driver.get("https://www.techwithtim.net/")

search = driver.find_element("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:
        # 获取所有entry-summary元素的列表
        headers = article.find_elements(By.CLASS_NAME, "entry-summary")
        # 遍历列表逐个提取文本
        for header in headers:
            print(header.text)
finally:
    driver.quit()

注意事项

错误栈里你写的是posted-on类,但代码里是entry-summary,要确保目标元素的类名和代码中的一致,避免无效匹配。

内容的提问来源于stack exchange,提问作者AARON SIMMONS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 11:00:56