【Python】Python_or_Selenium 不打开谷歌浏览器运行脚本

这段代码演示了如何使用Selenium Python库在无头模式下打开Chrome浏览器,并自动导航到百度首页,输入关键词'selenium'进行搜索,然后打印页面标题。Selenium是一个强大的Web自动化测试工具,可以用于网页交互和数据抓取。

1.导入相关库

from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.chrome.service import Service

2.指定【chromedriver.exe】得路径。

# 设置驱动路径
path = Service(r'C:\Program Files\Google\Chrome\Application\chromedriver.exe')

3.调用网页。

# 设置驱动路径
path = Service(r'C:\Program Files\Google\Chrome\Application\chromedriver.exe')
# 设置options参数
option = webdriver.ChromeOptions()
# 浏览器不提供可视化界面
option.add_argument('--headless')
# 隐藏正受到自动测试软件的控制
option.add_experimental_option("excludeSwitches", ["enable-automation"])
# 指定浏览器分辨率
option.add_argument('window-size=1920x1080')
# 最大化运行/全屏窗口
# option.add_argument('--start-maximized')
driver = webdriver.Chrome(service=path, options=option)

driver.get("https://www.baidu.com")
print(driver.title)
driver.find_element(By.ID,"kw").send_keys("selenium")
time.sleep(1)
driver.find_element(By.ID,"su").click()
time.sleep(1)
print(driver.title)
driver.quit()

完整代码:

from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.chrome.service import Service
# 设置驱动路径
path = Service(r'C:\Program Files\Google\Chrome\Application\chromedriver.exe')
# 设置options参数
option = webdriver.ChromeOptions()
# 浏览器不提供可视化界面
option.add_argument('--headless')
# 隐藏正受到自动测试软件的控制
option.add_experimental_option("excludeSwitches", ["enable-automation"])
# 指定浏览器分辨率
option.add_argument('window-size=1920x1080')
# 最大化运行/全屏窗口
# option.add_argument('--start-maximized')
driver = webdriver.Chrome(service=path, options=option)

driver.get("https://www.baidu.com")
print(driver.title)
driver.find_element(By.ID,"kw").send_keys("selenium")
time.sleep(1)
driver.find_element(By.ID,"su").click()
time.sleep(1)
print(driver.title)
driver.quit()

结果展示:
在这里插入图片描述

如有雷同或侵权请告知删除!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值