【问题标题】:With Open with Selenium Driver用 Open with Selenium Driver
【发布时间】:2023-01-26 04:19:19
【问题描述】:

您知道在 Python 中如何使用 with open() 子句打开文件,是否可以使用该子句打开 selenium 驱动程序以便它在您完成后自动关闭驱动程序?记得关闭我打开的驱动程序是我经常忘记的事情,我只是想知道是否有更好的方法。

这就是我所说的开放条款的意思。

with open([INSERT FILE NAME HERE], [INSERT ACCESS MODE HERE]) 作为文件名: [插入代码]

【问题讨论】:

  • 欢迎来到堆栈溢出。我不太明白。如果您想以这种方式使用 Selenium 驱动程序,“文件名”和“模式”是什么? “打开”和“关闭”它们到底意味着什么?

标签: python selenium web-scraping


【解决方案1】:

你需要context manager,代码就像

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time
class MySeleniumContextMgr():
    def __init__(self):
        print("build a driver")
        self.driver=webdriver.Chrome(executable_path="./chromedriver")
         
    def __enter__(self):
        print("All coding logic")
        self.driver.get("https://simpleappdesigner.pythonanywhere.com/")
        time.sleep(10)
        return self
     
    def __exit__(self, exc_type, exc_value, exc_traceback):
        print("Driver on quit!")
        self.driver.quit()
with MySeleniumContextMgr() as mydriver:
    print("done")

所以打印将是

build a driver
All coding logic
done
Driver on quit!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    相关资源
    最近更新 更多