admin管理员组文章数量:1321144
Selenium隐藏浏览器页面
背景
在工作,学习中,我们常常会使用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/'
#创建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/'
#浏览器启动选项
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
总结
掌握一门技术的最佳途径就是实践,好记性不如烂笔头,让咱们一起去实践学习吧!
版权声明:本文标题:Selenium隐藏浏览器页面 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/biancheng/1727325501a1236628.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论