问题描述:我遇到的问题是,当我运行代码时,它首先打开 chrome 浏览器并打开 google.com 网站,然后无缘无故地关闭它。 这是我的代码:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
opts = Options()
opts.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36")
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver_service = Service(executable_path=PATH)
driver = webdriver.Chrome(service=driver_service,options=opts)
driver.get("https://www.google.com/")
print("connected to: " + driver.title)
我期望的是:我的机器人将留在 google.com 并且不会关闭它! 例如:根据视频 https://www.youtube.com/watch?v=Xjv1sY630Uc 在 9:37 分钟,他运行了他的机器人,一个不会关闭窗口的机器人,并将其与我的机器人的行为进行了比较对我来说,它确实关闭了窗口(我不明白为什么它会打开并立即用我的机器人关闭窗口)
添加此代码并尝试:
options = Options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(service=driver_service,options=options)
不要忘记在 chromedriver.exe 路径中添加双斜杠“
\\
”。
从终端运行代码,如下所示......python -i scriptname.py。 这将保留外壳,因此您的程序可以运行。