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

for循环第二次迭代触发AttributeError的BeautifulSoup爬虫问题

问题原因

    1. 核心变量名冲突:你导入时将BeautifulSoup类别名为soup,但在首次循环中执行了soup = soup(driver.page_source, "lxml"),直接将soup变量的指向从类重写为第一次解析得到的文档对象,第二次循环再调用soup()时是在调用文档对象而非解析类,最终返回了ResultSet对象,调用select方法时触发属性错误。
    1. 驱动关闭逻辑错误:driver.quit()被放在for循环内部,首次循环结束就会关闭Chrome驱动,就算解决变量冲突,第二次循环也无法正常调用驱动加载页面。
    1. 内置函数名占用:代码中使用sum、list作为自定义变量名,会覆盖Python内置的同名函数,容易引发后续逻辑异常。

修复方案

  1. 将解析后的文档对象变量名改为和别名不冲突的名称,比如page_soup
  2. 把driver.quit()移到for循环外部,所有链接处理完成后再关闭驱动
  3. 替换自定义的sum、list变量名为非内置名称
  4. 可根据页面加载速度适当调整强制等待时长,避免页面未加载完成就执行解析逻辑

修复后完整代码如下:

import re
from selenium import webdriver
from bs4 import BeautifulSoup as soup
from time import sleep
import csv

filename = 'Author CSV.csv' 
with open(filename, 'r') as csvfile:
    driver = webdriver.Chrome(executable_path='C:/Users/Curious Beats/Downloads/chromedriver.exe')
    datareader = csv.reader(csvfile)
    for row in datareader:
        try: 
            url = row[0]       
            driver.get(url)
            sleep(2) # 可根据实际加载速度调整
            # 修改变量名避免覆盖类别名
            page_soup = soup(driver.page_source, "lxml")
            list_header = []
            header = page_soup.select('div.z-list.mystories')
            for items in header:
                try:
                    follows = items.get_text().split()
                    list_header.append(follows[follows.index('Follows:')+1])
                except:
                    continue
            # 避免占用内置list、sum函数名
            follows_num_list = [re.sub(',', '', _) for _ in list_header]
            for i in range(0, len(follows_num_list)): 
                follows_num_list[i] = int(follows_num_list[i]) 
            follows_sum = sum(follows_num_list)
            print(follows_sum)
        except IndexError:
            print('blank')
    # 所有循环跑完再关闭驱动
    driver.quit()

内容的提问来源于stack exchange,提问作者curious beats

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:09:01