赞
踩
在工作,学习中,我们常常会使用selenium来获取网页上的数据,编完完整程序之后,实现真正意义上的自动化获取,此时我们会发现在运行中往往会弹出浏览器页面,在调试过程中,这很方便,但是跑自动化时,我们就需要将浏览器隐藏在后台运行即可。这样就不会影响其他工作的进行。
主要是通过修改浏览器启动选项进行设置,其实就是将driver=webdriver.Chrome()
换成一下三行代码即可,涉及代码如下:
#浏览器启动选项
option=webdriver.ChromeOptions()
#指定为无界面模式
option.add_argument('--headless')
# option.headless=True 或者将上面的语句换成这条亦可
#创建Chrome驱动程序的实例
driver=webdriver.Chrome(options=option)
下面通过实例来展示,实现结果:
在这里我列出一个我认为不错的方法,分享给小伙伴们:
首先,是不隐藏浏览器的正常写法如下:
from selenium import webdriver
from selenium.webdriver.common.by import By
url='https://www.baidu.com/'
#创建Chrome驱动程序的实例
driver=webdriver.Chrome()
#打开浏览器并获取此网址的信息
driver.get(url)
#根据定位条件定位内容,并输出
content=driver.find_element(By.XPATH,'//*[@id="s-top-left"]/a[1]')
print(content.text)
#关闭浏览器
driver.close()
运行结果如下:此时是有浏览器页面弹出的。
D:\workplace\venv\Scripts\python.exe D:\workplace\venv\111.py
新闻
Process finished with exit code 0
通过修改浏览器启动选项,来设置浏览器的显隐:
from selenium import webdriver from selenium.webdriver.common.by import By url='https://www.baidu.com/' #浏览器启动选项 option=webdriver.ChromeOptions() #添加启动选项,指定为无界面模式 option.add_argument('--headless') # option.headless=True 或者将上面的语句换成这条亦可 #创建Chrome驱动程序的实例 driver=webdriver.Chrome(options=option) #,打开浏览器并获取此网址的信息 driver.get(url) #根据定位条件定位内容,并输出 content=driver.find_element(By.XPATH,'//*[@id="s-top-left"]/a[1]') print(content.text) #关闭浏览器 driver.close()
运行结果如下,此时浏览器页面无弹出。
D:\workplace\venv\Scripts\python.exe D:\workplace\venv\111.py
新闻
Process finished with exit code 0
掌握一门技术的最佳途径就是实践,好记性不如烂笔头,让咱们一起去实践学习吧!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。