111.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # -*- coding: utf-8 -*-
  2. # Author : Charley
  3. # Python : 3.10.8
  4. # Date : 2025/8/12 16:10
  5. from selenium import webdriver
  6. from selenium.webdriver.chrome.options import Options
  7. from selenium.webdriver.common.by import By
  8. import time
  9. def open_baidu_with_options():
  10. # 配置Chrome选项
  11. chrome_options = Options()
  12. chrome_options.add_argument("--headless=False") # 显示浏览器窗口
  13. chrome_options.add_argument("--start-maximized") # 最大化窗口
  14. chrome_options.add_argument("--no-sandbox")
  15. chrome_options.add_argument("--disable-dev-shm-usage")
  16. # 启动浏览器
  17. driver = webdriver.Chrome(options=chrome_options)
  18. try:
  19. # 打开百度网站
  20. driver.get("https://www.baidu.com")
  21. # 等待页面加载
  22. time.sleep(3)
  23. # 验证是否成功打开百度
  24. if "百度" in driver.title:
  25. print("成功打开百度首页")
  26. print(f"页面标题: {driver.title}")
  27. else:
  28. print("页面加载可能存在问题")
  29. # 可以在这里进行其他操作,比如搜索
  30. # search_box = driver.find_element(By.ID, "kw")
  31. # search_box.send_keys("Selenium")
  32. # search_button = driver.find_element(By.ID, "su")
  33. # search_button.click()
  34. # time.sleep(3)
  35. except Exception as e:
  36. print(f"发生错误: {e}")
  37. finally:
  38. # 关闭浏览器
  39. driver.quit()
  40. if __name__ == "__main__":
  41. open_baidu_with_options()