Python自动化selenium
如果出现卡住不打开,就把驱动放当前目录并指定
python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time
import os
def open_baidu():
# 获取当前目录中的chromedriver.exe的绝对路径
current_dir = os.path.dirname(os.path.abspath(__file__))
chromedriver_path = os.path.join(current_dir, "chromedriver.exe")
# 设置Chrome浏览器选项
chrome_options = webdriver.ChromeOptions()
# 使用当前目录中的chromedriver.exe
service = Service(executable_path=chromedriver_path)
# 初始化Chrome浏览器
print("正在初始化Chrome浏览器...")
driver = webdriver.Chrome(service=service, options=chrome_options)
# 打开百度网站
print("正在打开百度网站...")
driver.get("https://www.baidu.com")
# 最大化浏览器窗口
driver.maximize_window()
# 等待10秒,以便查看页面
print("成功打开百度首页")
time.sleep(10)
# 关闭浏览器
driver.quit()
print("浏览器已关闭")
if __name__ == "__main__":
try:
open_baidu()
except Exception as e:
print(f"发生错误: {e}")
input("按Enter键退出...")