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

Python AttributeError:Booking类实例无land_first_page属性问题求助

Python类实例化问题:Selenium Booking类报错分析与解决

问题背景

作为Python类初学者,在学习爬虫课程时,继承webdriver.Firefox实现Booking类,实例化过程中遇到属性错误与页面加载异常。

原实现代码

import os
from selenium import webdriver


class Booking(webdriver.Firefox):
    def __init__(self, driver_path=r"C:/SeleniumDrivers"):
        self.driver_path = driver_path
        os.environ['PATH'] = self.driver_path
        super(Booking, self).__init__()
        
    def const_url(self, BASE_URL="https://www.booking.com/"):
        BASE_URL = self.BASE_URL

    def land_first_page(self):
        self.get(BASE_URL)

执行代码与问题现象

执行以下代码块:

booking = Booking()
with Booking() as bot:
    bot.land_first_page

触发AttributeError:

Traceback (most recent call last):
  File "d:\AUIVVII\Udemy\AutomatingEV\BookingScraping\Booking\booking.py", line 23, in <module>
    bot.land_first_page
AttributeError: 'Booking' object has no attribute 'land_first_page'

同时出现两个无头Firefox实例,无内容加载且其中一个很快关闭。后续更换其他网站测试,报错消失但仍无法执行预期的页面加载操作。

错误原因分析与修复

核心错误点

  • const_url方法逻辑倒置:试图将实例属性赋值给局部变量,实际应为self.BASE_URL = BASE_URL,导致实例未绑定BASE_URL属性。
  • land_first_page方法变量引用错误:直接使用未绑定到实例的BASE_URL,需改为self.BASE_URL。
  • 方法未实际调用:bot.land_first_page仅引用方法对象,未加括号触发执行。
  • 重复实例化:booking = Booking()创建了未被使用的额外实例,导致多浏览器窗口启动。

修复后代码

import os
from selenium import webdriver


class Booking(webdriver.Firefox):
    def __init__(self, driver_path=r"C:/SeleniumDrivers"):
        self.driver_path = driver_path
        # 追加路径而非覆盖原有PATH,避免破坏系统环境变量
        os.environ['PATH'] += os.pathsep + self.driver_path
        super().__init__()  # Python3可简化super调用语法
        self.BASE_URL = "https://www.booking.com/"  # 初始化时直接绑定基础URL
        
    def land_first_page(self):
        self.get(self.BASE_URL)

# 正确执行逻辑:单实例+调用方法
with Booking() as bot:
    bot.land_first_page()

错误原因详解

  1. 属性绑定失败:原const_url方法中BASE_URL = self.BASE_URL是反向赋值,不仅没给实例绑定BASE_URL,还会因self.BASE_URL未定义触发隐性错误,最终导致land_first_page方法无法找到有效变量,引发属性错误。
  2. 方法调用遗漏括号:不带括号的bot.land_first_page只是获取方法对象,不会执行页面加载逻辑,必须加()才会触发get请求。
  3. 冗余实例化:booking = Booking()创建的实例未被使用,却启动了额外浏览器进程,with语句创建的实例会在代码块结束后自动关闭,因此出现“一个窗口很快关闭”的现象。

内容的提问来源于stack exchange,提问作者Sarp Yy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:12:51