繁体   English   中英

Selenium window 在导入“请求”模块时立即关闭

[英]Selenium window closes instantly when "requests" module is imported

我正在尝试将 Selenium 和 Beautiful Soup 与 Python 一起使用,但有一个相当奇怪的问题 - Selenium window 仅在未导入请求模块时保持打开状态,否则它会保持打开状态 1 秒然后关闭。
重要的是,只有当我在另一个文件中创建 class 时才会发生这种情况- 当我在同一文件中创建 class 时,它会保持正常打开状态。 下面是两个版本的代码——第一个 window 保持打开状态,第二个 window 立即关闭:

1:作品

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from test import Watcher

service = Service("C:\Program Files (x86)\Development\chromedriver.exe")
driver = webdriver.Chrome(service=service)

tw = Watcher(driver)
tw.open_browser()

# OTHER FILE CALLED test
class Watcher:
    def __init__(self, driver):
        self.driver = driver

    def open_browser(self):
        self.driver.get("https://www.google.com")

2:关闭

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from test import Watcher
import requests

service = Service("C:\Program Files (x86)\Development\chromedriver.exe")
driver = webdriver.Chrome(service=service)

tw = Watcher(driver)
tw.open_browser()

# OTHER FILE CALLED test
class Watcher:
    def __init__(self, driver):
        self.driver = driver

    def open_browser(self):
        self.driver.get("https://www.google.com")

我想知道这是否与 urllib3 中的 Keep-Alive 和连接池有关,即使程序代码中没有使用请求模块。

当你的程序终止时,HTTP 连接被释放,浏览器 window 关闭。

添加这个,你会看到浏览器 window 保持打开状态,直到程序完成运行。 该程序只是正常地完美终止而没有错误。

from time import sleep
for _ in range(10):
    sleep(1)

[编辑] 我有办法!

detach (Boolean) — 当驱动程序发送退出命令时浏览器是否关闭。

请参阅Class:Selenium::WebDriver::Chrome::Options

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from watcher import Watcher
import requests

service = Service("C:\Program Files (x86)\Development\chromedriver.exe")
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(service=service, options=options)

tw = Watcher(driver)
tw.open_browser()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM