未定义变量'driver'/不创建新的chrome实例

2024-05-10 01:20:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图调用一个click函数,最后是在我的/main.py文件中。在

/主.py

"""Start Point"""

from data.find_pending_records import FindPendingRecords
from vital.vital_entry import VitalEntry
import sys
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import pandas as pd

if __name__ == "__main__":
    try: 
        # for PENDING_RECORDS in FindPendingRecords().get_excel_data(): begin to loop through entire directory

            PENDING_RECORDS = FindPendingRecords().get_excel_data()
            # Do operations on PENDING_RECORDS

            # Reads excel to map data from excel to vital
            MAP_DATA = FindPendingRecords().get_mapping_data()

            # Configures Driver
            VITAL_ENTRY = VitalEntry()

            # Start chrome and navigate to vital website
            VITAL_ENTRY.instantiate_chrome()

            # Begin processing Records
            VITAL_ENTRY.process_records(PENDING_RECORDS, MAP_DATA)

            # Save Record
            VITAL_ENTRY.save_contact(driver)

            print (PENDING_RECORDS)
            print("All done")

    except Exception as exc:
        # print(exc)
        raise

/至关重要_条目.py

^{pr2}$

我在提示中不断出现此错误:

Traceback (most recent call last):
  File "main.py", line 32, in <module>
    VITAL_ENTRY.save_contact(driver)
NameError: name 'driver' is not defined

我不想创建一个新的chrome会话或窗口。。。我也试过把这个链接到我上面的VITAL_ENTRY.process_records(PENDING_RECORDS, MAP_DATA)上。正如您所看到的,我已经导入了驱动程序;并且我正在上面的调用中使用它-我不想创建一个新的浏览器实例。在

以下是.instantiate_chrome()

def instantiate_chrome(self):
    """Create Chrome webdriver instance."""
    self.options.headless = config.HEADLESS

    if not self.options.headless:
        self.options.add_argument("--start-maximized")

    self.options.add_argument('--disable-infobars')
    self.options.add_argument('--disable-gpu')

    self.driver = webdriver.Chrome(options=self.options)
    self.driver.set_page_load_timeout(30)
    self.driver.implicitly_wait(15)
    self.driver.get(config.VITAL_URL)

Tags: frompyimportselfdatadriverchromeoptions
1条回答
网友
1楼 · 发布于 2024-05-10 01:20:18

因此,创建浏览器会话,然后再也不会将其从该函数中传递出去。如果您想在其他地方使用它,您的instantiate_chrome()代码需要return driver,然后您需要按照我在前面的注释中所述的方式分配它

driver= VITAL_ENTRY.instantiate_chrome()

相关问题 更多 >